Append once. Read the growing past.
Step through decoding and see keys and values accumulate in separate banks for each layer.
Preparing the 3D view…
Keep keys and values
Each layer retains the keys and values of earlier tokens. The violet bank stores keys; the green bank stores values. Columns are token positions and rows are three illustrative layers.
Append the new token
Changing the token count highlights the newest column in amber. Earlier columns stay in place. Thin paths from the current query show that attention still reads every cached key and uses the corresponding values.
Account for growing memory
Each tile stands for a whole per-token tensor, not one scalar. Head and feature dimensions are collapsed. This is a conceptual dynamic cache with three layers, not a measured memory layout or latency benchmark.
The equation behind the motion
Kₜ = concat(Kₜ₋₁, kₜ); Vₜ = concat(Vₜ₋₁, vₜ)
Synthetic inputs with explicit geometric assumptions. Rotate the view and inspect the model above.
Read the primary sourceCount the memory behind the cache
Separate the number of tokens from the number of key/value heads. Both directly affect storage.
Reduced motion is on. Use Previous and Next to inspect each state.
bytes = 2 × batch × layers × tokens × KV heads × head dim × element bytes
Store keys and values separately
At 1,024 tokens and 8 KV heads, these tensors use 0.125 GiB across 32 layers in this fixed configuration.
Explore the inputs and calculations
Show the memory calculation
2 × batch × layers × tokens × KV heads × head dimension × bytes per element
2 × 1 × 32 × 4,096 × 8 × 128 × 2 = 536,870,912 bytes.
The first 2 counts separate key and value tensors. Changing a trained model’s number of KV heads is an architectural change, not a free serving toggle. This comparison isolates storage, not quality or latency.
Does a KV cache make each new token’s attention cost constant?
No. In dense full-context attention, the new query still reads the growing prefix. The cache avoids recomputing old keys and values; it does not remove those reads.