Inferensys

Glossary

Cache Eviction

Cache eviction is the algorithmic policy that determines which parts of a transformer model's KV cache to discard when allocated GPU memory is exhausted during long sequence generation.
Governance lead reviewing model governance framework on laptop, policy documents visible, executive office setup.
CONTEXT WINDOW MANAGEMENT

What is Cache Eviction?

Cache eviction is a critical memory management policy in transformer inference, determining which data to remove from the limited GPU memory allocated for the KV cache.

Cache eviction is the algorithmic process of selecting and removing entries from a Key-Value (KV) cache when its allocated GPU memory is full, to make space for new computations during long sequence generation. In transformer models, the KV cache stores intermediate attention states for previously processed tokens to avoid redundant computation. When the cache reaches capacity, an eviction policy—such as Least-Recently-Used (LRU)—must decide which cached vectors to discard, directly impacting generation speed and context coherence.

Common eviction strategies include LRU, which discards the oldest unused attention states, and more complex attention-score-based policies that prioritize retaining tokens with high aggregate attention. This process is a core component of context window management, balancing the trade-off between computational efficiency and the model's effective working memory. Poor eviction can lead to performance degradation or context loss, making its design crucial for long-context applications like document summarization or extended dialogues.

CONTEXT WINDOW MANAGEMENT

Key Cache Eviction Algorithms & Policies

When a model's KV cache reaches its allocated GPU memory limit, an eviction policy must determine which cached key-value pairs to discard to make room for new tokens. The choice of algorithm directly impacts generation quality, latency, and computational efficiency.

01

Least-Recently-Used (LRU)

The Least-Recently-Used (LRU) algorithm evicts the cached key-value pairs for the tokens that were accessed farthest in the past. It operates on the principle that recently used context is more likely to be needed again for coherent continuation.

  • Implementation: Typically uses a doubly-linked list and a hash map for O(1) access and eviction.
  • Impact on LLMs: Effective for maintaining local coherence in dialogue but can discard critical long-range dependencies from the beginning of a document.
  • Example: In a 4k context window, if the 1,000th token hasn't been attended to in many generation steps, its KV cache is a prime candidate for eviction.
02

First-In-First-Out (FIFO)

The First-In-First-Out (FIFO) policy evicts cached tokens in the order they were computed, regardless of recent usage. It treats the KV cache as a simple circular buffer.

  • Mechanism: The oldest key-value pairs are overwritten first as new tokens are generated.
  • Trade-off: Extremely simple and low-overhead but can be highly disruptive, as it may evict foundational context (e.g., system prompts or core document premises) needed for the entire session.
  • Use Case: Sometimes used in high-throughput, streaming inference where absolute minimal management overhead is required.
03

Least-Frequently-Used (LFU)

The Least-Frequently-Used (LFU) algorithm evicts the key-value pairs for tokens that have been referenced the least number of times during the generation session.

  • How it works: Maintains a frequency counter for each cached position. The token with the smallest count is evicted.
  • LLM Consideration: Can preserve foundational tokens that are repeatedly attended to (e.g., a character's name in a story) but may retain stale, high-frequency tokens that are no longer relevant.
  • Challenge: Requires additional metadata (frequency counts) and can suffer from 'cache pollution' where an initially high-frequency token becomes obsolete.
04

Attention-Score-Based Eviction

Attention-score-based eviction uses the model's own attention mechanism to decide what to keep. It evicts tokens whose key vectors received the lowest aggregate attention scores from recent queries.

  • Rationale: Directly targets semantic relevance; tokens that the model itself "ignores" are safe to remove.
  • Process: Computes a rolling sum of attention scores for each cached key. Periodically evicts tokens below a threshold.
  • Advantage: More semantically informed than LRU/FIFO. Can help preserve narratively important but temporally distant context.
  • Overhead: Requires tracking or sampling attention distributions, adding computational cost.
05

Random Eviction

Random eviction selects cached tokens for removal uniformly at random. It is a stochastic, non-deterministic policy.

  • Characteristics: Zero management overhead and can be surprisingly effective in large caches due to statistical dispersion.
  • Drawback: Unpredictable; may occasionally evict critical context, leading to sudden coherence breaks or factual errors in generation.
  • Application: Rarely used as a primary policy in production LLM serving but serves as an important baseline in cache performance research.
06

Size-Aware & Hybrid Policies

Modern systems often employ hybrid or size-aware policies that combine multiple signals for intelligent eviction.

  • Examples:
    • LRU-K: Evicts based on the time of the K-th-to-last reference, better resisting one-time spikes.
    • Adaptive Replacement Cache (ARC): Dynamically balances between recency (LRU) and frequency (LFU) lines.
    • Model-Aware Policies: Integrate token importance scores from the model's logits or intermediate activations.
  • LLM-Specific Design: The optimal policy often depends on the task—LRU for chat, attention-based for long-document QA—leading to runtime-switchable eviction strategies.
KV CACHE MANAGEMENT

Cache Eviction Algorithm Comparison

A comparison of primary algorithms used to determine which Key-Value (KV) cache entries to discard when GPU memory is full during long-context or extended generation tasks.

Algorithm / MetricLeast-Recently-Used (LRU)First-In-First-Out (FIFO)Least-Frequently-Used (LFU)Random Replacement (RR)

Core Eviction Policy

Discards the token least recently attended to.

Discards the oldest token in the cache.

Discards the token with the lowest historical access count.

Discards a randomly selected token.

Implementation Overhead

Moderate (requires tracking recency)

Low (simple queue management)

High (requires frequency counters & decay)

Very Low (no state tracking)

Best For

Conversational agents, interactive sessions

Streaming data with clear temporal decay

Static reference text with repeated queries

Simple baselines, uniform access patterns

Worst For

Cyclic access patterns, looping sequences

Sequences where early context remains critical

Sudden shifts in topic or focus

Predictable, performance-critical workloads

Temporal Locality Exploitation

Frequency Sensitivity

Deterministic Eviction

Typical Hit Rate (General Text)

0.7 - 0.85

0.5 - 0.7

0.6 - 0.8 (if stable)

~0.5

Common Variants

LRU-K, ARC (Adaptive Replacement Cache)

Second-Chance FIFO (Clock)

LFU with Aging

Weighted Random

Use in LLM Inference

Widely adopted for its intuitive fit

Less common; can discard critical system prompts

Rare due to overhead and shifting attention

Used as a baseline in research evaluations

CACHE EVICTION

Implementation & System Context

Cache eviction is the critical process of determining which data to remove from a finite memory store when it reaches capacity. In AI inference, this governs the management of the KV cache during long text generations.

01

Least-Recently-Used (LRU)

The Least-Recently-Used (LRU) algorithm evicts the cached data that has not been accessed for the longest time. It's based on the principle of temporal locality.

  • Mechanism: Tracks access timestamps or maintains an ordered list. The oldest entry is discarded first.
  • KV Cache Application: When the GPU memory allocated for the Key-Value cache is full, the attention states for the tokens generated earliest in the sequence are typically evicted.
  • Pro: Simple and effective for many access patterns.
  • Con: Can perform poorly if older context is suddenly needed again, potentially harming coherence in very long generations.
02

First-In-First-Out (FIFO)

The First-In-First-Out (FIFO) policy evicts cached data in the order it was added, regardless of how recently it was used.

  • Mechanism: Operates like a queue. New entries are added to the tail; the entry at the head is removed when eviction is required.
  • System Context: Often used in streaming or pipeline buffers where data has a strict chronological lifespan.
  • Pro: Extremely low overhead, no need to track access frequency.
  • Con: Can evict frequently used, critical data simply because it was loaded earlier, leading to poor cache hit rates.
03

Least-Frequently-Used (LFU)

The Least-Frequently-Used (LFU) algorithm evicts the cached data with the smallest number of accesses over a recent period.

  • Mechanism: Maintains a counter for each cache entry that increments on every access. The entry with the smallest count is evicted.
  • Consideration for LLMs: While less common for pure KV cache eviction, variants are relevant for semantic cache systems that store frequent query-embedding pairs. It prioritizes retaining commonly referenced context patterns.
  • Pro: Excellent for stable, repetitive access patterns.
  • Con: Can become biased, where once-popular but now stale data occupies cache, and it requires more metadata (counters).
04

Random Replacement (RR)

Random Replacement (RR) selects a victim cache entry at random when eviction is necessary.

  • Mechanism: Uses a pseudo-random number generator to pick an index within the cache to evict.
  • System Context: Used in high-performance computing and some CPU caches due to its simplicity and lack of state overhead.
  • Pro: Zero metadata overhead and fast decision time. Avoids pathological worst-case scenarios of deterministic policies.
  • Con: Performance is unpredictable and generally lower on average than LRU or LFU for most workloads. Not typically used for KV cache management where coherence is critical.
05

Eviction in Transformer KV Cache

In transformer inference, KV Cache eviction is directly tied to GPU memory limits. The cache stores (Key, Value) matrices for previous tokens to avoid recomputation.

  • Trigger: Eviction occurs when the pre-allocated cache memory is exhausted during the generation of a long output sequence.
  • Typical Policy: A form of LRU applied to sequence positions. The earliest tokens in the sequence (often from the initial prompt or early generation) are evicted first, as their attention influence typically decays.
  • Impact: Evicting essential context can cause the model to "forget" early instructions or narrative details, leading to coherence breakdown or task failure. This necessitates context management strategies like summarization or selective retention.
06

Cache Admission Policies

An admission policy determines whether new data is inserted into the cache at all, working in tandem with the eviction policy.

  • Always Admit: Every new piece of data (e.g., new token's KV states) is written to cache, forcing an eviction. This is standard for streaming KV caches.
  • Probabilistic Admission: New data is only cached with a certain probability (e.g., TinyLFU). This filters out one-hit wonders, items accessed only once, preserving cache space for more valuable entries.
  • Size-Aware Admission: Considers the size of the new item versus the size of potential victims. A large item might not be cached if it would evict many smaller, potentially more useful items.
  • Context: In LLM systems, admission is usually "always admit" for the KV cache, but these policies are highly relevant for higher-level semantic or document caches built atop the model.
CACHE EVICTION

Frequently Asked Questions

Cache eviction is a critical inference optimization technique for managing the finite memory allocated to a model's key-value (KV) cache during long text generations. These questions address the algorithms, trade-offs, and practical implications of deciding what to discard when the cache is full.

Cache eviction is the algorithmic process of selectively removing entries from a transformer model's KV cache when the allocated GPU memory is exhausted, allowing the generation to continue without re-computing the entire sequence from scratch.

During autoregressive generation, each new token produced depends on all previous tokens. The KV cache stores pre-computed intermediate states (keys and values) for these previous tokens, which saves immense computational cost. However, this cache has a fixed size in memory. When generating a very long sequence (e.g., a lengthy document), the cache fills up. An eviction policy must then decide which cached states to discard to make room for new tokens, balancing the need to retain the most important contextual information against the memory constraint. This is a fundamental challenge in context window management for long-context models.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.