The cache contract
For every layer and stored position, preserve the key and value tensors needed by future queries, then append exactly one new pair per decode step.
Reuse computation. Spend memory.Step through prompt prefill and autoregressive decode. Compare cached keys and values with repeated projection work, then change attention architecture, model shape, precision, and batch size to calculate memory.
Only the new token's projections are appended during decode.
Every decode step repeats projections for the growing prefix.
A decoder-only transformer generates one token at a time. The prompt first passes through a prefill phase that processes many positions in parallel. During decode, each new token creates one query and attends to keys and values from every earlier position.
Without caching, the model would reproduce key and value projections for the complete prefix on every step. A KV cache stores those per-layer tensors after they are computed. The next step appends one new key and one new value per KV head, then uses the stored prefix in attention.
The cache removes repeated projection work, but it does not make decode constant-cost. The new query still compares against a context that grows by one position, cache memory grows linearly with sequence length and batch size, and reading the stored tensors consumes memory bandwidth. Long-context serving is therefore shaped by both arithmetic and memory movement.
The simulator's projection-work ratio is intentionally narrow: it compares how many token positions undergo K/V projection with and without reuse. It is not a latency claim. Kernel fusion, parallelism, batching, hardware, quantization, sampling, and attention implementation all influence wall-clock performance.
The 3D left lane appends one K/V pair on each generated token. The right lane flashes every visible pair because all prefix projections are repeated in the teaching comparison. When the logical sequence exceeds the visible capacity, the scene shows the newest positions while the formulas continue using the full token count.
For every layer and stored position, preserve the key and value tensors needed by future queries, then append exactly one new pair per decode step.
Reuse computation. Spend memory.Prefill handles the prompt with parallel matrix operations. Decode handles one or a few new positions while reading a large, growing cache.
Double sequence length, batch size, layers, KV heads, head dimension, or bytes per element and the cache grows by the same factor.
Caching K and V avoids recomputing projections, but a new query still forms attention scores over prior positions unless a different attention strategy changes that work.
Real systems must reserve, page, evict, share, or compress cache blocks while handling requests with different prompt and generation lengths.
At each layer, learned matrices map the token representation into query, key, and value vectors. Queries are used for the current attention operation; prior queries are not needed by future tokens in standard decoder self-attention.
The cache keeps K and V for every retained token and layer. Position encoding, layout, quantization metadata, and allocator overhead can add implementation-specific storage beyond the simplified tensor formula.
The current query scores the cached keys, masking any disallowed positions. Softmax weights then mix the cached values. Cache hits remove projection repetition, not the need to read and use the prefix.
After the step computes the new projections, they become part of the cache for the next token. The sequence dimension grows monotonically unless a window, eviction rule, compression scheme, or request termination changes it.
Continuous batching interleaves decode steps from requests with different lengths. Paged allocators reduce fragmentation and allow cache blocks to move or share without requiring one large contiguous reservation per sequence.
Each query head has its own key and value head. This maximizes head-specific representations but makes cache size proportional to the full attention-head count.
MHASeveral query heads share each K/V head. GQA reduces cache memory and projection bandwidth while retaining more K/V groups than a single-head design.
GQAAll query heads share one key head and one value head. MQA minimizes KV-cache size and bandwidth, trading away per-query-head K/V diversity.
MQALower-precision cache storage reduces memory and bandwidth. Useful implementations must manage scales, outliers, conversion cost, accuracy, and hardware support.
BitsA long sequence multiplies every per-token cache byte. Grouped-query attention limits the head dimension of that growth, but batch size and layer count can still make the aggregate allocation large.
No. It stores numerical key and value tensors produced inside each attention layer. Applications may separately retain token IDs, text, logits, or conversation state, but those are not the transformer KV cache itself.
A past query was used to produce the past token's attention output. Future tokens need their own new query and the prior keys and values. Standard decode therefore caches K and V rather than old Q tensors.
No. It removes repeated K/V projection for the prefix, but the new query still attends over a growing sequence and reads a growing cache. Attention kernels, windows, sparsity, and hardware determine the exact scaling.
Systems can share identical prompt prefixes when identity, position handling, model state, and isolation policy permit it. Prefix caching needs careful correctness, lifecycle, and privacy boundaries.
The request may stop, reject additional input, truncate, slide a window, compress memory, or use architecture-specific context management. A cache cannot exceed the positions the model and serving policy support.
Keys influence attention scores and values influence the mixed output. Quantization error accumulates across layers and long contexts, especially for outliers or sensitive heads, so precision choices require evaluation.
No. It counts K/V projection token-work in this teaching comparison. End-to-end latency includes attention, feed-forward layers, memory transfer, synchronization, sampling, and implementation overhead.
KV caching turns repeated projection into persistent state. Efficient inference comes from understanding both sides of that exchange: compute reuse and a cache that grows with every retained token.
Explore text-message AI assistants