KV Cache Eviction by Budget
Each cache entry is [request_id, bytes_used, last_used]. Implement evict_kv_requests(entries, new_bytes, capacity) and return the IDs to evict in eviction order. If existing usage plus new_bytes exceeds capacity, evict oldest entries first, breaking equal timestamps by input order. Return [] if the new allocation fits. If new_bytes > capacity, return all entry IDs because even an empty cache cannot fit the request. Inputs are nonnegative and request IDs are unique. Do not mutate entries.
Explore the underlying concept with illustrative inputs. This experiment is separate from the problem’s test cases.
KV caching
Decode tokens while keeping keys and values aligned in a bounded window.
Retained token positions
Dense example: 1 request × 1 tokens × 32 layers × 8 KV heads × 128 dimensions × 2 bytes × 2 (K and V) = 0.125 MiB.
Change the experiment
keys = (keys + [new_key])[-capacity:]
values = (values + [new_value])[-capacity:]Try it yourself
Set a capacity of two and decode five tokens. Which pairs remain, and how many were evicted?
1 tokens decoded. 1 cached pairs; 0 evicted.
Cached keys and values avoid recomputing their projections for earlier tokens. Attention still reads the retained cache.
Playback pauses in hidden tabs and offscreen. With reduced motion enabled, use the timeline or Next step.Examples
A guided view of the published example, not a trace of your code.
[[["a",4,1],["b",3,3],["c",2,2]],4,10]["a"]Start with the input values shown in this example.
Input: entries = [["a",4,1],["b",3,3],["c",2,2]], new_bytes = 4, capacity = 10
Output: ["a"]
Explanation: evict oldest
Input: entries = [["a",2,1],["b",2,1]], new_bytes = 3, capacity = 5
Output: ["a"]
Explanation: stable tie
Hint 1
Calculate current usage before sorting.
Hint 2
Use original input position to break timestamp ties.