ELLMEngineering Large
Language Models
Download PDF

Chapter 05

What the Model Keeps During Generation

On this page

Reusing a prefix requires state. A transformer retains keys and values for previous positions; other architectures retain compressed or recurrent representations. We begin with the ordinary cache and then examine what changes when history is no longer stored token by token.

Reuse the part that does not change

After prefill, the model selects a new token and processes it through the decoder. At each layer, the new token produces a query, key, and value. Its query reads eligible earlier keys and values, and its own key/value pair joins the history for future positions.

Why can the earlier keys and values be reused? In a causal decoder, an earlier position cannot depend on tokens added later. With the same weights, position conventions, and earlier prefix, its computed representation remains valid. This equivalence assumes inference behavior: dropout is disabled, and no sequence-length-dependent transform retroactively changes earlier positions. Recomputing under those conditions would obtain the same mathematical result, subject to floating-point differences between execution paths. The KV cache stores these per-layer keys and values.

Caching does not remove the dependence on history. The new query must still read the relevant cached entries. Thus two costs grow with context: stored state and the amount of history potentially read during decode. The distinction will matter in the next chapter, where capacity and bandwidth become separate questions.

Count what is in the cache

Let L be the number of layers, H_kv the number of key/value heads per layer, d their head width, and b the bytes per stored value. For B equally long sequences with S cached tokens each:

2026-10-12T12:02:54.979645 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Multiply keys and values by sequences, layers, positions, heads, head width, and element size.

The factor two counts one key and one value. This is logical tensor storage. It excludes allocator rounding, temporary workspaces, and any extra copies. For unequal lengths, replace B*S by the sum of cached lengths. This form assumes every layer uses the same KV geometry and retention policy. In a heterogeneous decoder, sum S_l H_kv,l (d_k,l b_k,l + d_v,l b_v,l) over layers and requests instead; a sliding-window layer and a full-attention layer need not retain the same number of positions.

Our illustrative decoder has 32 layers, hidden width 4096, 32 query heads, eight KV heads, and head width 128. With two-byte KV elements, each cached token requires 2*32*8*128*2 = 131,072 bytes, or 128 KiB. A 4,096-token request therefore uses 512 MiB of logical KV state. This is in addition to the model weights, which can be shared across requests.

The unequal query and KV head counts are deliberate. Grouped-query attention, or GQA, lets several query heads share one KV head. Standard multi-head attention uses a separate KV head for every query head; multi-query attention shares one KV head across all query heads. At fixed remaining dimensions, changing from 32 KV heads to eight divides the cache by four. The model must be trained or adapted for its chosen architecture; this is not a free layout conversion. The GQA paper studies the quality and state tradeoff.

Invalidate at the first changed position

Suppose positions zero through two were cached and position one is edited. Keep only position zero's K/V at every layer. Recompute positions one onward with their original global indices; deeper-layer state at later positions depends on the changed token even if those later input IDs were not edited. The lab executes this partial-prefix repair and compares its logits with a completely fresh pass. Simply replacing the edited token's first-layer key is insufficient.

A speculative branch has the same dependency problem after rejection. A pure attention decoder can truncate each layer's cache to the accepted boundary. A hybrid also needs a recurrent-state snapshot at that boundary, or replay from an earlier one. Its grammar cursor, random stream and pending tool/action decisions may need rollback too. No rejected branch may publish an external effect merely because its tokens were computed.

Distinguish storing less from reading less

The cache equation suggests two obvious interventions: reduce the amount stored per position, or reduce the number of positions retained or read. They do not have the same effect on the computation.

Quantizing a cache changes the numerical representation of its values. Sharing KV heads changes the architecture's projected state. A sliding window restricts which past positions a query may read. Once a position falls outside that window, a direct attention lookup cannot recover it, although information may already have propagated through other layers. Merely selecting fewer keys does not prove that the implementation has stopped storing the others.

Consider three eligible scores [0,0,log(8)] with values [0,0,10]. Dense softmax attention returns 8. A selector that omits the third position returns zero. The selected computation can be implemented perfectly and still lose the evidence the model needed. This is why a faster attention mechanism needs quality evaluation as well as numerical tests on its chosen support.

A learned latent cache stores a smaller representation for each token and reconstructs or transforms information as needed. Its storage still generally grows with sequence length, but the per-token factor changes. Part VII develops the projection algebra of Multi-head Latent Attention (MLA) alongside the models that use it. At this point, the important distinction is between shortening each stored record and replacing the record collection with a summary.

Reading fewer positions, sharing heads, and compressing token state are different choices. None can be inferred solely from the label “efficient attention.”
Open full diagram ↗

Reading fewer positions, sharing heads, and compressing token state are different choices. None can be inferred solely from the label “efficient attention.”

A recurrent state summarizes the history

A recurrent model updates a fixed-size state as each token arrives. To see what that entails, consider a scalar state beginning at zero and the update h_new = 0.5*h_old + u. Inputs [2,0,4] produce states [2,1,4.5].

The state after the third input is one number, regardless of how many earlier inputs there were. But a later query cannot generally reconstruct the first input from 4.5. Other histories could produce the same state. Fixed storage is possible because the model retains a summary rather than an independently addressable representation of every position.

Learned recurrent models use much richer states and input-dependent writes, retention, and reads. A matrix memory, for example, can associate key directions with value directions. Different update rules govern whether a new observation accumulates with old information or corrects an existing association. We defer their detailed equations to Part VII; understanding the transformer cache does not require learning every recurrence at once.

The serving consequence is already visible. Restoring an earlier prefix may require a saved recurrent state or replay from a supported boundary. Keeping only the current state is not enough to undo an arbitrary number of updates. A paged KV allocator solves a different problem and cannot by itself supply recurrent rollback.

A hybrid needs both kinds of state

Some models use attention in selected layers and recurrent updates in others. Their memory is the sum of the growing attention caches and the recurrent states, including any auxiliary convolution history. Counting only the attention layers understates the constant part; treating every layer as full attention overstates the sequence-dependent part.

For a hypothetical 32-layer model with eight GQA layers using our earlier geometry, attention storage is 32 KiB per token, or 64 MiB at 2,048 tokens. Suppose the remaining 24 layers each use 16 recurrent heads with a 128*128 FP32 matrix per head. Those matrices require 24*16*128*128*4 = 24 MiB per sequence. The combined logical state is at least 88 MiB before auxiliary buffers.

At one token, the 24 MiB recurrent term can be larger than a small all-attention cache. At long contexts, the attention-only cache continues growing in every layer. A statement that one architecture “uses less memory” therefore needs a context length and a complete state inventory. The detailed mechanisms and dated model examples in Part VII build on this accounting.

Translate state into a workload constraint

Consider summarizing a document with a full-attention decoder. Both the source document and the generated summary contribute tokens to the retained history. A short requested summary therefore does not imply a small cache: a long source can dominate it. A completion over a short prefix can use far less state even if it generates the same number of output tokens. Input length and output length must be recorded separately when describing the workload.

A cancelled request should release state no longer in use. A reused prefix must match the relevant model and input semantics. These are consequences of what the cache represents, rather than properties of a particular application. The next chapter combines this per-request state with shared weights and temporary work to estimate the resources a complete workload needs.

Exercises and worked answers

  1. Why does a causal decoder not need to recompute an earlier key after appending a token? The earlier position cannot read the appended token, so its representation is unchanged under the same model and prefix conventions.
  2. How much KV storage does the illustrative decoder use at 16,384 tokens? 16,384*128 KiB = 2 GiB per sequence, before physical-allocation overhead.
  3. Can a sparse attention kernel repair an omitted relevant key? No. Correct computation over the selected keys cannot restore evidence excluded by selection.
  4. Can a hybrid restore an earlier prefix by deleting later KV entries? Not by that operation alone. It must also restore the corresponding recurrent and auxiliary state, or replay from a saved boundary.