Module 2 · Lesson 2.5 of 2.5

KV-Cache Memory & Performance

Lesson 2.4 showed what the KV cache holds. This lesson asks how big it is and what it costs to read during decode.

Learning goal. Derive the raw KV-cache size from a model’s attention configuration, compute it for real-looking configurations in correct units, see how it grows with context length and concurrency, and explain why reading it can dominate decode-time memory traffic.

Default worked example. A hypothetical decoder with L = 32 layers, HKV = 8 KV heads, head dimension D = 128, cache stored in BF16, holding a 4,096-token context. Its cache is exactly 536,870,912 bytes = 512 MiB.

Builds on. 2.3 KV heads (MHA/MQA/GQA) and 2.4 cache shape.

2.5.1 Deriving KV-cache memory

The problem. Before deploying a model you need to know how much memory each request’s cache will occupy. The answer follows directly from the conceptual shape from Lesson 2.4: for each layer, keys and values are each a tensor of shape [T, HKV, D].

M_KV = 2 L T H_KV D B bytes. This counts raw keys and values for one sequence, excluding other memory.

Step 1: one token in one layer

For one new token, each KV head in a layer stores one key vector and one value vector, each with D numbers, and each number takes B bytes.

bytes per token per layer = 2 · HKV · D · B

Example: 2 × 8 × 128 × 2 = 4,096 B = 4 KiB. The 2 counts the key and the value; forgetting it is the most common mistake.

Step 2: one token across all layers

Every attention layer has its own projections, so every layer keeps its own K and V for the token. Nothing is shared across layers in this model.

bytes per token = 2 · L · HKV · D · B

Example: 32 × 4,096 = 131,072 B = 128 KiB per cached token.

Step 3: a whole sequence

A sequence with T cached tokens stores that per-token amount T times.

MKV = 2 · L · T · HKV · D · B bytes
MKV
Raw key and value storage for one sequence, in bytes. Not total GPU memory.
2
One key tensor and one value tensor (K and V are the same size here).
L
Number of attention layers, each with its own cache.
T
Cached tokens in the sequence: prompt plus processed generated tokens (Lesson 2.4: tokens processed, not merely sampled).
HKV
Key/value heads per layer: equal to query heads for MHA, 1 for MQA, between for GQA (Lesson 2.3).
D
Head dimension: numbers per key or value vector (assumed equal for K and V).
B
Bytes per stored element: 4 for FP32, 2 for BF16/FP16, 1 for FP8/INT8.

Worked example: 2 × 32 × 4,096 × 8 × 128 × 2 = 536,870,912 bytes. Because every factor is a power of two, this is exactly 229 bytes = 512 MiB.

Engineering implication. Memory is linear in every factor. Doubling context doubles it; cutting KV heads from 32 to 8 (MHA-style to GQA-style) cuts it by 4×; halving bytes per element halves it. Query heads do not appear, because queries are not cached.

Decimal versus binary units

Two unit systems are in everyday use and are easy to mix up. Decimal (SI) units are powers of 1,000; binary (IEC) units are powers of 1,024. GPU memory is often marketed in GB while tools such as nvidia-smi report MiB, so always say which you mean.

The worked-example cache in both unit systems
UnitBytes per unit536,870,912 B is
MB (megabyte)1,000,000 = 106536.87 MB
MiB (mebibyte)1,048,576 = 220512 MiB exactly
GB (gigabyte)1,000,000,000 = 1090.537 GB
GiB (gibibyte)1,073,741,824 = 2300.5 GiB exactly

1 MiB is about 4.9% larger than 1 MB, and 1 GiB is about 7.4% larger than 1 GB. At the scale of a deployment (tens of GiB) that gap is several gigabytes, enough to turn “fits” into “does not fit”.

2.5.2 KV-cache memory calculator

The calculator applies the boxed formula to any configuration and to many concurrent sequences. With N sequences of possibly different lengths Ti, the raw total is a sum; for equal lengths it collapses to a product:

Mtotal = Σi 2 · L · Ti · HKV · D · B = N · 2 · L · T · HKV · D · B (if every Ti = T)

Unequal example (worked example config): three requests with 1,000, 4,000 and 8,000 cached tokens hold 13,000 tokens × 131,072 B = 1,703,936,000 B ≈ 1.70 GB ≈ 1.59 GiB. Only the total token count matters, not how it is split. The calculator below assumes equal lengths.

KV-cache memory calculator

What this shows
Raw K and V bytes for one sequence and for N concurrent sequences, from the formula above, in exact bytes, decimal and binary units.
Try
Load Example C (MHA-style) and compare it with Example A, then change only T, then only B.
What to notice
Each input scales the result proportionally. Example C needs 4× Example A because it has 4× the KV heads; nothing else differs.
Illustrative configurations (hypothetical; they set L, HKV, D):
Raw KV-cache storage for the current inputs
QuantityFormula (bytes)BytesDecimal (SI)Binary (IEC)

Assumptions: K and V have the same head dimension; every layer has the same HKV and caches every token; contiguous logical tensors; no cache sharing between sequences. The example configurations are illustrative, not the specifications of any particular released model. FP8/INT8 KV quantization usually also stores small per-block or per-head scale factors, which this calculator does not model.

What this number is not. It is the raw size of the K and V tensors only, not total GPU memory. It excludes:

  • model weights (usually the largest single item);
  • activations and temporary buffers for the forward pass (including attention workspace and logits);
  • allocator metadata, block tables and fragmentation;
  • padding and partially filled blocks in block-based allocators (2.5.3);
  • the serving framework’s own memory, CUDA context and communication buffers;
  • savings from prefix sharing or KV compression/quantization schemes beyond the chosen B. For example, multi-head latent attention (MLA, DeepSeek-V2) caches a compressed latent per token, so the formula above does not apply to it.

2.5.3 Memory versus context length

The formula says memory is proportional to T: a straight line through zero whose slope is the per-token cost times N. The chart uses the model configuration from the calculator. Context length moves along each line; comparing KV-head counts reveals their relative per-token cost.

Raw KV memory versus context length

What this shows
Aggregate raw KV memory for N equal-length sequences as T grows, for your HKV (solid, circles) and a reference HKV (dashed, squares).
Try
Use the calculator to compare 8, 32 and 1 KV heads. Change concurrency there; both chart lines use the same model dimensions, precision and sequence count.
What to notice
Lines stay straight; N and HKV only change the slope. The gap between the lines is a constant ratio, reference ÷ current.

Change model configuration in the calculator. The reference has 32 KV heads (MHA for 32 query heads); this calculator does not specify your query-head count. The plotted range includes at least 32,768 tokens and expands automatically to include the calculator’s selected context.

  • Your HKV: solid line, circle markers
  • Reference HKV = 32: dashed line, square markers
Raw KV-cache memory versus cached context lengthLoading chart.
Shared calculator configuration: 32 layers, D = 128, B = 2 bytes, N = 1. The y-axis uses binary units; exact bytes are in the table.
Chart data (same values as the plotted markers)
Cached tokens TH_KVReference

Assumptions: idealised linear model with exactly T × per-token bytes per sequence; all N sequences have the same length; no block rounding, fragmentation, weights or activations; L, D and B held at the shared calculator values within each plot.

Real allocators grow in steps

Serving engines rarely grow one token at a time. A common design reserves KV memory in fixed-size blocks of tokens; vLLM, for example, exposes a block_size setting, the “size of a contiguous cache block in number of tokens” (vLLM engine arguments); 16 tokens is a commonly used value and is used in the example below. With 16-token blocks, a sequence of T tokens reserves ⌈T / 16⌉ × 16 token slots, so the true curve is a staircase that sits on or slightly above the straight line.

Example (worked-example config): T = 4,097 needs ⌈4,097 / 16⌉ = 257 blocks = 4,112 slots. The 15 unused slots cost 15 × 131,072 B = 1,966,080 B ≈ 1.88 MiB. The waste per sequence is at most one partly filled block, so it matters most for many short sequences and little for a few long ones. How blocks are allocated, shared and freed is the subject of Lesson 4.4 (PagedAttention) in Module 4; here, just remember that the linear formula is a lower bound for what an allocator reserves.

2.5.4 Bandwidth during decode

Memory capacity is one cost of the cache. The other is reading it. In each decode step, the new token’s query must be compared with every cached key and must weight every cached value (Lesson 2.4: caching avoids recomputing K/V, not attention itself). So the attention layers read the cached K and V of every attended position, in every layer, at every step.

  1. Longer context T
  2. More cached K/V per sequence
  3. More KV bytes read per decode step
  4. Greater memory-bandwidth demand
Simplified causal chain. Caveats: attention variants that attend to fewer positions (for example sliding windows), cache data already resident in on-chip memory, kernel optimisations and hardware all change how strongly the last step follows.

KV bytes read per decode step

Assume the new query attends to all T cached positions and every cached byte is read from GPU memory exactly once per step. Then one decode step for one sequence reads approximately the whole cache:

KV bytes read per step ≈ 2 · L · T · HKV · D · B

Read the next number with these caveats. It is a first-order traffic estimate, not a timing model. It assumes every cached byte is read exactly once per step: caches resident in on-chip memory, kernel optimisations, overlap of compute and memory traffic, and attention variants that read fewer positions (such as sliding windows) all change it. Real step time depends on kernels, parallelism and hardware.

Worked example: for the default configuration at T = 4,096, every generated token requires reading ≈ 536,870,912 B = 512 MiB of K/V for that one sequence, and the amount grows by 128 KiB with each token generated. With 32 such sequences in a decode batch, a step reads ≈ 16 GiB (≈ 17.18 GB) of K/V. For scale: the weights of a hypothetical 8-billion-parameter model in BF16 are about 16 GB, so in this example (this batch size and context, under the assumptions above) the KV reads are of the same order as the weight reads.

Arithmetic intensity: why KV reads are hard to hide

Arithmetic intensity is FLOPs performed per byte moved from memory. Work whose intensity is below the hardware’s compute-to-bandwidth ratio (commonly tens to hundreds of FLOPs per byte on modern data-centre GPUs) tends to be limited by memory bandwidth rather than arithmetic.

  • Attention during decode. Per layer and KV head, a step reads 2 · T · D · B bytes of K and V. Each of the g query heads sharing that KV head does about 2D FLOPs per key (scores) and 2D per value (weighted sum), so about 4 · g · T · D FLOPs. Intensity ≈ 2g / B: with 32 query heads over 8 KV heads (g = 4) in BF16, about 4 FLOPs per byte; MHA (g = 1) about 1. Simplified: softmax and scaling are ignored.
  • Weight matrix multiplies. A weight matrix is read once per step and used by every sequence in the batch, so its intensity grows roughly with batch size (about b FLOPs per byte for batch b in BF16).
  • The asymmetry. Each sequence has its own cache, so KV reads do not amortise across the batch. Raising decode batch size improves weight-read utilisation, but total KV traffic grows with Σ Ti and attention’s intensity stays low. Long contexts therefore make decode increasingly dominated by KV reads, and fewer KV heads (GQA/MQA) or smaller B reduce those bytes directly.

Key takeaway. KV reads do not amortise across the batch. A weight matrix is read once and serves every sequence; each sequence reads only its own cache, so total KV traffic grows with every sequence and every token of context. Only fewer KV heads or fewer bytes per element reduce it. The GPU module derives this with a calculator: Module 3, lesson 3.5, “Cached does not mean free to read”.

Limits. Decode is often bandwidth-sensitive but not always bandwidth-bound: with short contexts, small batches dominated by fixed overheads, or large batches whose weight multiplies become compute-heavy, other limits appear. Prefill attention, with many queries per cached key, has much higher intensity. There is no universal latency equation; see the caveats before the worked example.

IO-aware attention kernels such as FlashAttention (Dao et al., 2022) reduce memory traffic by avoiding materialising the full attention matrix in GPU memory; they still have to read the cached K and V. Their internals are outside this module.

2.5.5 Exercise: sizing a deployment’s KV cache

Use the boxed formula (or work by hand, then check with the calculator) to size a deployment’s cache. Choose the unit you computed in; GB and GiB are graded as different units.

Why this number alone cannot decide a deployment

Knowing the raw KV total is necessary but not sufficient to say whether a GPU deployment works:

  • Weights come first. Model parameters usually occupy more memory than any single item, and they must fit alongside the cache.
  • Activations and workspace. The forward pass needs temporary buffers, especially during prefill of long prompts.
  • Allocator overhead and fragmentation. Block rounding, block tables and fragmentation make reserved memory exceed the raw total.
  • Sharding across GPUs. With tensor parallelism, KV heads are typically split across GPUs, so each GPU holds only part of the cache (and if there are fewer KV heads than GPUs, heads may be replicated, increasing the total). The per-GPU figure, not the total, has to fit.
  • Request-length variance. Real requests are not all 8,000 tokens; the sum Σ Ti fluctuates, and output length is unknown when a request is admitted.
  • Headroom. Engines reserve a configurable fraction of GPU memory (vLLM’s gpu_memory_utilization, the fraction of GPU memory the engine may use, for example) and need slack for spikes; running at 100% leads to preemption or out-of-memory failures.
  • Bandwidth, not just capacity. Even when the cache fits, 2.5.4 shows that reading it every step affects throughput and latency.

Further reading: vLLM documentation (KV cache memory management and configuration); Ainslie et al., GQA; Shazeer, MQA.

2.5.6 Where this leads: why the GPU matters

Lesson 2.5 established two facts: the KV cache is large (2.5.1–2.5.3), and every decode step has to read it (2.5.4). So decode is often limited by memory bandwidth, the number of bytes per second that can move between a GPU’s memory and the units that do the arithmetic. What this module has not explained is where that memory sits, how fast it is, and why moving bytes can cost more than computing with them.

Next: Module 3, GPU architecture. It explains how a GPU executes work, how its memory hierarchy is organised, how tiling reuses bytes, and how arithmetic intensity and the roofline tell you whether bandwidth or arithmetic is the limit. Then: Module 4, efficient attention uses that vocabulary to cut traffic and fragmentation: FlashAttention avoids writing the full score matrix to GPU memory, PagedAttention avoids reserving one contiguous run per sequence, and sharing avoids storing the same K/V twice. Lessons 4.1–4.3 open with the Module 3 terms they need.