Evict KV cache blocks with an LRU policy
Why it matters vLLM and SGLang prefix caching evict KV blocks with LRU-style policies.
Prefix caches keep KV blocks for popular prompts and evict the least recently used block when full.
Write lru_kv(accesses, capacity). accesses is a list of block ids. Simulate an LRU cache. Return (hits, misses, final) where final is the list of cached ids from least to most recently used.
def lru_kv(accesses, capacity)Example
lru_kv([1, 2, 1, 3], 2) has hits 1, misses 3, final [1, 3].
Understand the idea
Prefix caching keeps the KV blocks of popular prompts in GPU memory so repeated system prompts skip prefill. When memory is full, a block must be evicted, and least recently used (LRU) picks the block nobody has touched for the longest. A hit refreshes the block so it becomes the newest. Worked example: accesses [1, 2, 3, 1, 4, 2], capacity 3. 1, 2, 3 are misses, cache [1, 2, 3] from oldest to newest. 1 is a hit and moves to the end: [2, 3, 1]. 4 is a miss, evict the oldest 2: [3, 1, 4]. 2 is a miss, evict 3: [1, 4, 2]. Result: hits 1, misses 5, final [1, 4, 2]. Rule: keep an ordered list or ordered dict from least to most recent; on a hit, move the id to the most recent end; on a miss, if full, remove the least recent, then add the id at the most recent end. Forgetting to refresh on hits turns it into FIFO, which evicts hot blocks. Used in: vLLM and SGLang prefix caches, and caches in general.