443. 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 1
lru_kv([1, 2, 1, 3], 2) has hits 1, misses 3, final [1, 3].
Example 2
Input: accesses = [1, 2, 3, 1, 2, 3], capacity = 2
Output: (0, 6, [2, 3])
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
collections.OrderedDict with move_to_end and popitem(last=False).
Hint 2
OrderedDict keeps insertion order.
Hint 3
Move a hit to the end; pop from the front when over capacity.
Common mistakes
- Not refreshing on hit.
- Evicting before inserting when the block was a hit.
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.
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].
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.