Large Language ModelsInference & Performance Optimization
How does head-first KV-cache eviction preserve expensive agent history for faster multi-turn LLM serving?
Question 308 of 309 · Updated
On this page
- The problem: conventional eviction can discard the most expensive history to rebuild
- 1. First separate the two eviction decisions
- 2. Why later tokens cost more to recompute
- 3. Penelope's eviction policy: LRU chooses the history, head-first chooses the segment
- Why block-level release matters
- 4. The unusual part: reuse a cached suffix after an earlier gap
- 5. Phantom prefill: rebuild the gap in the same execution batch
- A small numerical illustration
- 6. GPU and CPU memory must share one logical eviction order
- 7. How Penelope differs from nearby KV-cache techniques
- 8. What the evaluation actually demonstrates
- 9. Important limitations and production questions
- 10. A practical rollout plan
- Interview-ready summary
The problem: conventional eviction can discard the most expensive history to rebuild#
Long-running coding and research agents repeatedly submit requests containing much of their earlier context: system instructions, tool schemas, prior messages, tool outputs, and newly appended results. Serving systems cache key/value (KV) tensors so that a later request with a matching prefix can skip prefill for that prefix.
The cache is finite. Under memory pressure, a serving engine must reclaim blocks. Conventional prefix caches generally preserve the beginning of a sequence and evict from its tail. That is sensible for ordinary prefix matching: many future requests can share the same early tokens, while fewer may share the latest suffix.
But it creates a compute-cost asymmetry. Under full causal attention, recomputing a token near the end of a long context requires attention over a longer preceding history than recomputing an earlier token. If two eviction choices free the same number of tokens, dropping an early private segment can be cheaper to rebuild than dropping the later suffix.
Penelope explores this trade-off for multi-turn agent serving. Its central idea is to preserve the shared prefix, evict from the beginning of the remaining private history, and retain the later cached suffix. It then reconstructs only the missing historical range while reusing the suffix. This is not ordinary request preemption, cache compression, or moving the entire KV cache to CPU.
1. First separate the two eviction decisions#
A cache manager makes two logically different decisions:
- Which history should lose cache? A replacement policy such as least-recently-used (LRU) chooses a candidate history or branch.
- Which portion of that history should be released? A position-aware policy chooses the segment within the selected history.
These decisions are often conflated. LRU answers which cached history has been least recently useful; it does not determine whether the head or tail of that history is cheaper to recompute.
In a radix-tree prefix cache, shared token paths represent common prefixes. A leaf is not necessarily safe to evict if a running request still references it. Implementations also need to protect in-flight KV state. The position-aware decision must therefore respect both sharing and active references.
2. Why later tokens cost more to recompute#
For a causal Transformer, a token's attention computation depends on preceding tokens. Ignoring implementation-specific optimizations, the attention work associated with a token grows with its position in the sequence. Linear projections and feed-forward operations contribute a largely position-independent per-token cost, while attention adds a position-dependent component.
Suppose a cached history has a shared prefix of length P followed by a private history H. A later turn appends new tokens. If the system must reclaim B KV tokens, it can consider two broad choices:
- Tail eviction: release the latest B cached tokens. A future turn must rebuild those late positions, whose attention spans are long.
- Head-first private-history eviction: preserve the shared prefix and release B tokens from the beginning of H. A future turn rebuilds earlier positions, whose attention spans are shorter, while the later suffix remains available.
The number of missing tokens can be identical, but the recomputation cost need not be. This argument assumes full causal attention and unchanged model/token history. Sliding-window attention, recurrent-state architectures, sparse attention, or other attention semantics require their own cost model.
Penelope's paper illustrates the effect with Qwen3-8B on one H100: evicting about 30% of the cache from position 2K rather than from the end improved the next-request latency by 1.14× at an 8K context and 2.93× at 128K in that experiment. These are measured results for that setup, not universal multipliers.
3. Penelope's eviction policy: LRU chooses the history, head-first chooses the segment#
Penelope combines LRU history selection with head-first eviction within the selected history.
Its radix tree represents common prefixes as shared paths. When the cache needs space, the policy starts from an evictable LRU leaf and traces backward along the path. It stops when it reaches a boundary that must be preserved, such as:
- the root or beginning of the history;
- a parent with multiple children, indicating a shared-prefix boundary;
- a node still referenced by a running request;
- an already-missing KV segment.
The earliest eligible private position becomes the eviction start. The policy then releases KV in sequence order, moving to another eligible history if more space is needed.
This boundary logic matters. Simply evicting from token zero could destroy the shared system prompt and tool definitions reused by other sessions. Evicting from the head of a private history instead protects common content while targeting the portion that is cheaper to reconstruct.
Why block-level release matters#
A radix-tree node may contain many KV tokens. Releasing the entire node can free substantially more memory than the allocator actually needs. That over-eviction increases future recomputation and can trigger a feedback loop: excess eviction creates more misses, which creates more prefill work and memory pressure.
Penelope splits nodes at KV block boundaries and releases only the leading blocks needed to satisfy the current allocation. The remaining blocks in the same node stay cached.
The distinction is important:
- Node-level release may discard a large range because the tree node is the reclamation unit.
- Block-level release makes the reclamation amount closer to the requested memory budget.
A good policy therefore optimizes both *where* it starts eviction and *how much* it releases.
4. The unusual part: reuse a cached suffix after an earlier gap#
Conventional prefix lookup usually stops at the first missing block. That works when cache contents are always a contiguous prefix. Head-first eviction deliberately breaks that assumption: an earlier private segment may be missing even though a later suffix is still cached.
Consider this simplified token history:
[Shared prefix P] [Private segment H1] [Retained suffix S] [New tokens N]
cached evicted cached not computedThe retained suffix is still valid if the model, token sequence, positional interpretation, and relevant execution configuration are unchanged. But the new tokens N need the historical keys and values from H1 to compute attention correctly.
Penelope preserves enough radix-tree token metadata and parent/child structure to match through a region whose KV has been released. It can then identify both the missing historical range and the cached suffix beyond it. The missing range is marked as unavailable KV rather than being mistaken for a cache hit.
The returning request can consequently reuse:
- the cached shared prefix P;
- the retained suffix S;
- and compute only the missing H1 plus the newly appended N.
This is a more demanding cache contract than ordinary longest-prefix matching. The cache index must distinguish token-history presence from KV-data presence.
5. Phantom prefill: rebuild the gap in the same execution batch#
A later token cannot attend to H1 if its KV is absent. Penelope restores that missing segment using an internal prefill-only request called a phantom request.
The execution is conceptually:
- Match the returning request against the radix tree, including token paths whose KV is missing.
- Identify the missing historical segment H1 and the retained suffix S.
- Allocate KV blocks for H1.
- Create a phantom request that processes H1 at its original sequence positions but generates no user-visible output.
- Keep the real request responsible for the newly appended tokens N.
- Place the phantom and real requests in the same batch, with the original positional information preserved.
- At each Transformer layer, write the phantom's reconstructed K/V before the real request's attention consumes the restored history.
The important optimization is not that H1 is never recomputed. It must be recomputed because its KV was evicted. The gain comes from avoiding recomputation of S and arranging restoration so that the real request can use the rebuilt segment and retained suffix without running a separate full-history prefill.
The phantom request is an internal scheduling mechanism, not a second agent, a user request, or an additional generated answer. Its tokens count against the prefill token budget because the model still has to process them.
A small numerical illustration#
Assume a 100,000-token history consists of:
- 15,000 shared-prefix tokens;
- 55,000 private-history tokens;
- 30,000 later private tokens.
Suppose memory pressure requires reclaiming 10,000 KV tokens from the private portion.
A tail policy removes the final 10,000 tokens. A head-first policy removes 10,000 tokens immediately after the shared prefix. Both release the same KV capacity. On a returning request, the second policy can retain the later 45,000 private tokens and recompute the earlier 10,000-token gap, while the tail policy must rebuild the later 10,000 positions.
This is only an illustration of the position effect. Real performance also depends on block boundaries, attention implementation, batch composition, cache hit structure, and how much of the history is shared.
6. GPU and CPU memory must share one logical eviction order#
A two-tier cache introduces another failure mode. If GPU and CPU memory independently choose eviction victims, the combined system may violate the intended position-aware order.
For example, a segment could be migrated from GPU to a full CPU cache. If the CPU tier independently evicts a later segment while the GPU tier retains an earlier one, the final set of cached tokens no longer follows the intended head-first policy.
Penelope therefore treats GPU and CPU as one logical cache for deciding what is finally discarded. Each cached segment resides in only one tier at a time. Migration changes its location; it does not itself count as eviction. The logical eviction policy selects the final victim across both tiers before migration is coordinated.
When both tiers are full and a CPU-resident segment must be loaded into GPU memory, the system may need to exchange incoming and outgoing blocks. Penelope uses a small reserved CPU swap buffer and moves data in chunks:
- write outgoing GPU blocks into free swap-buffer blocks;
- load the requested CPU blocks into the newly available GPU blocks;
- reuse the CPU blocks vacated by the completed load for the next chunk;
- enforce transfer dependencies so a block is not overwritten before its previous transfer finishes.
Separate asynchronous transfer streams and CUDA events coordinate loads and offloads. Compute waits for the relevant load to finish before reading the KV data.
The design lesson is broader than this paper: a tiered cache should make replacement decisions over the logical data set, not let each physical tier independently destroy the global retention policy.
7. How Penelope differs from nearby KV-cache techniques#
- Ordinary prefix-cache LRU: chooses an idle cached block or leaf based on recency and generally preserves contiguous prefixes. It does not by itself retain a suffix beyond an evicted interior gap.
- Question 233, prefix-cache eviction: explains why idle reusable blocks are reclaimed under memory pressure and how misses affect prefill. Penelope changes the *position within a selected multi-turn history* and adds suffix recovery.
- Question 291, productive preemption: concerns active requests interrupted during generation, their recompute/offload/restore costs, and scheduling enough protected decode time to make progress. Penelope concerns completed or reusable agent histories retained across turns; it is not a policy for repeatedly preempting active decode requests.
- Question 293, queue-aware prefix scheduling: uses the waiting request queue to protect prefixes likely to be reused by queued requests. Penelope changes which positions within a history survive eviction and how missing interior segments are reconstructed.
- Question 299, hierarchical sparse-attention KV offloading: keeps sparse-attention history available across HBM, host DRAM, or pooled memory and fetches selected blocks during decode. Penelope is about eviction placement in multi-turn histories under full causal attention, then selective prefill recomputation and suffix reuse.
- Question 307, relative-position-dependent caching: reuses invariant prompt segments whose relative order is stable while absolute positions shift. Penelope assumes the same token history and positional interpretation for a returning session; it does not solve cross-position cache alignment.
- Pensieve and AsymCache: earlier work also exploits the fact that earlier history can be cheaper to recompute. Penelope's contribution is its agent-workload design: preserve shared prefixes, retain later suffix KV across a missing interior segment, and coordinate a single head-first eviction order across GPU and CPU tiers.
These distinctions prevent a common mistake: calling every method “KV offloading” or “cache eviction.” The cache identity, reuse contract, missing-data pattern, and recovery path are different.
8. What the evaluation actually demonstrates#
The Penelope study implements the design in SGLang and evaluates Qwen3-8B, Qwen3-32B, and Qwen3-235B-A22B-Instruct-2507-FP8. It uses coding-agent traces from Claude Code and FreeInference, with H100 and A100 systems and both GPU-only and GPU–CPU configurations.
Reported results include:
- On Claude Code GPU-only workloads, mean TTFT improves by 36–60% and mean job completion time by 27–37% over the evaluated SGLang baseline.
- On the FreeInference trace with three and four concurrent sessions, mean TTFT improves by 30% and 32%, while job completion time improves by about 2%. The paper explains that long tool waits dominate those sessions, so faster prefill affects only a small part of total session time.
- With GPU–CPU caching, mean TTFT improves by 46–76% and mean job completion time by 36–60% over a stronger SGLang offloading baseline that also counts CPU-resident prefixes for scheduling.
- In an ablation, the full combination of private-history-start eviction and block-level release reduces TTFT by 63% and JCT by 39% in the reported 8B Claude Code setup. Its hit rate is only 1.9 percentage points above tail eviction with the same block granularity, yet TTFT is a further 33% lower. That illustrates why hit rate alone does not measure the compute cost of a cache miss.
The authors also report correctness checks: greedy outputs were bit-identical to a no-eviction reference in their tested configurations, including recomputed missing segments and reused suffixes. Treat this as evidence for the evaluated model/runtime path, not a universal guarantee for every architecture, positional scheme, or serving engine.
9. Important limitations and production questions#
The policy is not universally optimal. It relies on position-dependent recomputation cost under full causal attention. Sliding-window, sparse, hybrid, or recurrent architectures can change which positions are expensive and which cached state is reusable.
Shared-prefix boundaries are critical. Evicting too early can damage cross-session reuse. A real implementation must track sharing, references, active readers, and session history changes correctly.
Interior gaps complicate scheduling. The engine must preserve token metadata, locate suffixes beyond missing KV, allocate restoration blocks, and account for phantom tokens in prefill budgets. A system that only supports contiguous prefix hits cannot simply enable head-first eviction.
Block size affects waste. Large reclamation units can release more KV than needed and erase the benefit of position-aware placement. Smaller blocks reduce over-eviction but may increase metadata and management overhead.
CPU capacity and bandwidth still matter. A unified logical cache avoids inconsistent replacement decisions; it does not make host memory unlimited or transfers free. Measure PCIe/NVLink topology, NUMA placement, copy concurrency, swap-buffer pressure, and load latency.
Scheduler policy changes the gain. Penelope's benefits are stronger when the scheduler favors histories with reusable cache. Under FCFS, more sessions can lose their private histories entirely, reducing the benefit of choosing where to evict. The paper reports smaller TTFT improvements under FCFS than under longest-prefix-match scheduling.
Tool waits dilute end-to-end gains. TTFT improvements do not automatically translate into similar job-completion improvements when agent sessions spend most of their time waiting for tools or external services.
The cache identity must remain valid. Reusing a suffix requires matching model weights/version, token IDs, positional semantics, attention configuration, adapter identity, and other inputs that affect KV computation. If those assumptions change, invalidate the relevant cache rather than reusing stale tensors.
10. A practical rollout plan#
- Classify the workload. Start with multi-turn agent sessions that repeatedly carry long histories. Measure context-length distribution, shared-prefix length, turn-to-turn growth, and cache reuse.
- Measure the position cost. On the target model and attention backend, compare recomputing equal-sized early and late segments. Do not assume the paper's ratios transfer to your stack.
- Map the cache structure. Identify shared prefixes, private history, active references, block boundaries, and the exact conditions under which a retained suffix remains valid.
- Add safe head-first eviction. Select the history by a replacement policy, locate the earliest eligible private position, and reclaim only the required blocks.
- Implement gap-aware matching. Keep enough token-path metadata to find retained suffixes beyond missing KV. Clearly distinguish a matched token path from a KV cache hit.
- Implement phantom prefill. Recompute missing historical ranges at their original positions and coordinate writes before the real request consumes the restored KV. Count the work in scheduler budgets.
- Unify tier decisions. If using host memory, make GPU and CPU placement part of one logical eviction policy. Test full-tier swaps and transfer races.
- Validate correctness. Compare deterministic outputs and per-position log probabilities against a no-eviction reference. Test different gap locations, chunked prefill, cache pressure, and concurrent sessions.
- Benchmark more than hit rate. Track TTFT, p95/p99 TTFT, job completion time, cache hit rate, recomputed tokens by position, bytes transferred, memory utilization, and tool-wait fraction.
- Canary by workload class. Begin with long-context agent sessions where history reuse is high. Keep conventional eviction as a fallback for unsupported attention types, cache-identity mismatches, and low-reuse traffic.
Interview-ready summary#
Head-first KV-cache eviction is a position-aware policy for multi-turn LLM histories. LRU selects which history to reclaim, but Penelope releases blocks from the beginning of that history's private portion while preserving shared prefixes and later cached suffixes. When the session returns, it uses a phantom prefill request to rebuild only the missing historical segment while the real request reuses the retained suffix and processes new tokens. A unified GPU–CPU cache preserves the same logical eviction order across tiers. The key insight is that equal-sized KV evictions can have very different recomputation costs because later causal-attention positions are more expensive to rebuild. It is useful for long, repeatedly reused agent histories, but requires gap-aware cache lookup, careful positional correctness, and workload-specific validation.
References
- 1.
- 2.SGLang Radix Cache Eviction Policiesgithub.com
- 3.vLLM Automatic Prefix Caching Designdocs.vllm.ai
- 4.
- 5.Multi-Segment Attention (AsymCache)arxiv.org
Related questions
- How do distributed position-independent KV caches coordinate remote reuse, parallel prefill, and cluster-wide resource allocation?
- How does relative-position-dependent KV caching reuse ordered prompt segments across changing agent turns?
- How does query-side adaptation enable recomputation-free position-independent KV-cache reuse in LLM serving?
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents