advanced32 min studyLesson 63 in Engineering

KV caches and inference memory

Account for attention state by layers, key-value heads, sequence length, precision, and concurrent requests.

On this page

What you’ll understand

  • Explain what cached keys and values save during causal decoding.
  • Calculate cache storage for multi-head and grouped-query attention.
  • Separate logical token state, allocation overhead, weights, and working memory.

Generating one more token does not require recomputing every earlier token's key and value projections. A causal Transformer can retain that state in a key-value cache and append new entries as decoding advances. The cache saves repeated computation, but it grows with the context held for every active sequence. An inference service that fits its weights comfortably can still run out of memory when long requests or many users arrive together.

Reuse earlier causal attention state

At each attention layer, the new query attends to keys and values associated with the existing prefix. Under ordinary causal decoding, earlier tokens' hidden representations do not change when future tokens are appended, so their projected keys and values remain reusable. The new token still needs its own projections and an attention operation over the retained context. Caching therefore removes repeated prefix computation; it does not make the cost of reading a growing context vanish.

Count key-value heads rather than assuming they equal query heads. Conventional multi-head attention stores a key and value head for every attention head. Multi-query attention shares one key-value head, while grouped-query attention uses an intermediate number. These architectures change cache size and attention structure. They are properties of trained model weights, not an arbitrary serving switch that can always be applied without adaptation or quality evaluation. Inspect the actual model configuration before budgeting.

MKV=2LhKVdhb∑i=1BTiM_{\mathrm{KV}}=2Lh_{\mathrm{KV}}d_hb\sum_{i=1}^{B}T_i
For dense full-context caching, L is layers, hKV key-value heads per layer, dh head width, b bytes per element, and Ti cached tokens in active sequence i. The factor two counts keys and values. This logical tensor estimate excludes allocation and metadata.↔ Scroll wide equations horizontally.

Logical state is not allocated memory

A naive contiguous allocation that reserves each request's maximum length wastes unused capacity and can fragment memory as requests finish at different times. PagedAttention instead organizes cache storage in blocks with a mapping from logical positions to physical blocks. The analogy to virtual memory explains flexible allocation, not a claim that device attention is implemented by an ordinary operating-system page fault. Block size trades internal waste against bookkeeping and kernel access patterns.

Prefix sharing can save physical storage only where the serving system establishes compatible reusable state. Matching text is insufficient if model revisions, tokenizer behavior, positions, attention masks, or other inputs differ. Sharing also requires an isolation policy so one tenant cannot infer another's private prompt through timing or cache behavior. Count shared physical blocks once when measuring actual allocation, but do not subtract speculative sharing from an admission budget unless the implementation guarantees that reuse.

Reserve room for growth and execution

Total device memory includes weights, cache, temporary attention buffers, activations, communication storage, and runtime allocations. Weight quantization does not automatically reduce cache precision; those are separate choices with separate quality and kernel requirements. Reserve a safety margin rather than assigning every remaining byte to prompts. A request's output grows its cache until termination, and beam search or branching can create several continuations whose storage depends on how prefixes are shared.

Admission and scheduling need both current use and expected growth. A fixed maximum output reservation is conservative but predictable; speculative overcommit needs a deliberate response when requests all grow together. Options include controlled preemption, recomputation, or rejection, each with a latency cost. Measure peak allocated memory and out-of-memory behavior under realistic length distributions. Reporting only an average cache length conceals the long-context tail that can determine whether the service survives a burst.

Mdevice≥Mweights+MKV+Mworkspace+MreserveM_{\mathrm{device}}\geq M_{\mathrm{weights}}+M_{\mathrm{KV}}+M_{\mathrm{workspace}}+M_{\mathrm{reserve}}
The inequality is a capacity requirement, not an equality predicting allocator behavior. Each term must reflect actual precision, execution topology, and the peak concurrent workload.↔ Scroll wide equations horizontally.

Count grouped-query cache bytes

A model has 32 layers, eight key-value heads per layer, head width 128, and two-byte cache elements. Sixteen independent requests each hold 4,096 tokens. Ignore padding, sharing, and allocator overhead.

  1. Each cached token requires 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or 128 KiB. This counts both keys and values at every layer.

  2. One 4,096-token request therefore needs 536,870,912 bytes, or 512 MiB. Sixteen requests need 8,589,934,592 bytes, or 8 GiB of logical cache.

  3. If the architecture had 32 key-value heads instead, the cache would be four times larger: 32 GiB for the same requests. Thirty-two query heads with only eight key-value heads still use the eight-head calculation.

The result

The example requires 8 GiB before weights, workspaces, extra output tokens, and allocation overhead. Query-head count alone would overestimate this grouped-query cache by four.

Explore the model

Interactive lab

Interactive lab · function

A visible scaling law with a different exponent

The lab plots y=ax², its tangent, and area from zero to x. Use it to contrast quadratic growth with the cache's linear token-count law. It does not plot KV bytes or model a memory allocator; the equation in this lesson supplies that calculation.

A visible scaling law with a different exponentThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forIdentify the actual scaling variable and exponent before extrapolating a memory requirement.

Check your understanding

A model has 32 query heads but eight key-value heads. Which head count belongs in the standard KV-cache storage formula?

Try it yourself

Using the worked model, four requests each have 2,048 prompt tokens and reserve 1,024 output tokens. Calculate the worst-case logical KV reservation, with no sharing.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Use 128 KiB per token and count the prompt plus reserved output for every request.

Compare with the solution

Each request reserves 3,072 tokens. Four requests reserve 12,288 token slots, requiring 12,288 × 131,072 = 1,610,612,736 bytes, or 1.5 GiB. This is a logical upper bound under the stated output cap; physical block rounding, execution workspace, and weights require additional capacity.

Take it with you

  • Caching reuses prefix projections while attention still reads retained context.
  • KV heads, both tensors, precision, and all active tokens determine logical storage.
  • Allocate for growth and overhead rather than treating free memory as a fixed prompt budget.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.