The KV cache stores the key and value vectors computed for earlier tokens, so the model does not recompute them at every step. But the cache cannot grow forever: the default dynamic cache grows as generation progresses, while for models using sliding window attention the cache stops growing when the window is reached, and older tokens start to be evicted. Choosing a cache is choosing an eviction policy: what the model forgets when the cache fills, and whether that forgetting breaks the conversation.
What you need
- The longest conversation you need to support, in tokens
- The model attention type: full or sliding window
- A test conversation that refers back to early messages
Step 1: Check how the cache grows for your model
Confirm whether your model uses full attention or sliding window attention. With sliding window layers, the cache never grows larger than the window, even if the maximum length you set is larger, and older tokens are evicted as new ones arrive.
Step 2: Pick the cache implementation for the length
Use the default dynamic cache for ordinary lengths, a fixed-size static cache when you need just-in-time compilation, and a quantized cache when memory is the constraint. Set max_cache_len on a static cache to pre-size it to the largest call you expect.
Step 3: Test the conversation as the cache fills
Run the test conversation that refers back to early messages and check the answers stay correct as the token count passes the window. If the model forgets the opening instruction, the eviction policy is dropping tokens the task needs.
Worked example: synthetic cache eviction test on 4 lengths
The table below is a synthetic example. It shows the expected result of testing cache behaviour; no model was run.
| Conversation length | Cache | Early message remembered? |
|---|---|---|
| 1,000 tokens | Dynamic cache | Yes |
| 8,000 tokens | Dynamic cache | Yes |
| 32,000 tokens | Sliding window cache | No – evicted |
| 32,000 tokens | Full attention cache | Yes |
Expected result (UNTESTED). the dynamic and full attention caches remember the early message, while the sliding window cache evicts it past the window. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- For assisted decoding, a sliding window layer is only usable while the token count is smaller than the window, or rejected draft tokens cannot be rolled back.
- A quantized cache trades memory for latency, and can harm latency when the context is short and memory is plentiful.
- A static cache pre-allocates its maximum size, so it wastes memory on short sequences.
- Offloaded caches move KV data to CPU, which saves GPU memory but costs generation throughput.
