Evict KV cache entries while keeping heavy hitters and recent tokens
Why it matters Heavy-hitter style eviction lets long-context generation run in a fixed memory budget with small quality loss.
Long generations can outgrow the KV cache. One family of methods keeps a fixed budget: always the most recent tokens, plus the older tokens that have collected the most attention so far (heavy hitters).
Write kv_keep(scores, budget, recent). scores is a length-T array of accumulated attention each cached token has received. If T <= budget keep everything. Otherwise always keep the last recent positions (recent < budget), then fill the remaining budget - recent slots with the highest-scoring positions among the older ones, ties going to the lower index. Return the sorted list of kept positions.
def kv_keep(scores, budget, recent)Example
scores [5, 1, 4, 0, 2, 3], budget 4, recent 2 gives [0, 2, 4, 5].
Understand the idea
Think of a small backpack for a long hike. You always carry what you need right now (the recent tokens), and from the older stuff you keep only what you used most often. In attention, the tokens that have received a lot of attention in the past tend to keep receiving it, so they are worth keeping. Worked example: scores [5, 1, 4, 0, 2, 3], budget 4, recent 2. Positions 4 and 5 are recent and kept. From 0 to 3, the two best scores are 5 at position 0 and 4 at position 2. Keep [0, 2, 4, 5]. Rule: keep = last r positions + top (budget - r) old positions by accumulated score. This caps KV memory for long chats and agents at a fixed size regardless of length.