Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
KV-Cache Eviction (Attention Sinks)
An LLM’s KV cache grows with every token, so long chats need a way to drop old entries without wrecking quality. StreamingLLM’s insight: keep the first few tokens (the "attention sinks") plus a sliding window of the most recent ones, and throw away the middle. Compute which tokens survive. Solve it in Python or TypeScript, with hidden tests.
The problem
A sequence has n tokens (indices 0…n-1) in the KV cache. Under a StreamingLLM eviction policy you keep the first sink tokens (attention sinks) and the most recent window tokens, evicting everything in between. Implement kv_keep(n, sink, window): return the sorted list of token indices that remain in the cache.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? open the hints under the problem, or Reveal solution is one click away.
Implement kv_keep(n, sink, window): form the set of sink indices and the set of recent-window indices, union them, and return the sorted result.
Examples and constraints 4 examples
n = 10, sink = 2, window = 3[0, 1, 7, 8, 9]n = 5, sink = 2, window = 3[0, 1, 2, 3, 4]n = 6, sink = 4, window = 4[0, 1, 2, 3, 4, 5]n = 3, sink = 10, window = 10[0, 1, 2]- Keep indices
0 … sink-1(attention sinks) andn-window … n-1(the recent window). - The two ranges may overlap or cover the whole sequence — return each surviving index once, sorted.
- Clamp to the sequence bounds: if
sinkorwindowexceedn, just keep what exists.
Hints 4 ideas
- Sink indices are
range(min(sink, n))— the first tokens, clamped to n. - Recent-window indices are
range(max(0, n - window), n)— the lastwindowtokens. - Union the two index sets so overlaps are not double-counted.
- Return them sorted. The evicted tokens are exactly the middle ones present in neither set.
Approach, complexity & discussion — open after you solve
Start from brute force
The direct version walks every index and keeps it if it is a sink or in the window: [i for i in range(n) if i < sink or i >= n - window]. It is correct, clamping included, because the test only ever runs on real indices, and it comes out sorted. But it costs O(n) time for O(k) output, where k is at most sink + window: a million-token stream with a 1,024-token budget scans a million indices to keep 1,024. The other quick version, list(range(sink)) + list(range(n - window, n)), is fast and wrong: it repeats overlapping indices and, for n = 3 with budgets of 10, invents tokens 3 to 9 and negative indices.
The approach
The survivors are two contiguous ranges, so build them from their bounds instead of testing every index. The reference kv_keep clamps each range to the sequence: sinks = set(range(min(sink, n))) holds the first tokens, and recent = set(range(max(0, n - window), n)) holds the last window. The min stops the sinks running past the end, and the max(0, …) stops the window starting at a negative index. sorted(sinks | recent) returns the union in order; the set union is what removes indices both ranges cover when sink + window reaches n.
The invariant: every index in the answer lies in [0, n) and in at least one range, and appears exactly once. The TypeScript kvKeep adds both ranges to one Set and sorts with (a, b) => a - b, because the default sort compares numbers as strings. Since both ranges are already sorted, concatenating range(0, a) and range(max(a, b), n), with a and b the clamped bounds, gives the same list in O(k) without a set.
t − window, into the evicted middle. That is why the incremental version in the follow-ups is O(1) per token.Walk through an example
For the first example, n = 10, sink = 2, window = 3, the two ranges do not touch, so five tokens survive and the middle five are evicted.
| step | expression | value |
|---|---|---|
| 1 | sinks = set(range(min(2, 10))) | {0, 1} |
| 2 | recent = set(range(max(0, 10 - 3), 10)) | {7, 8, 9} |
| 3 | sinks | recent | {0, 1, 7, 8, 9} |
| 4 | sorted(...) | [0, 1, 7, 8, 9]; tokens 2 to 6 are in neither range |
Complexity
Time O(k log k) for the k ≤ sink + window survivors: building the two clamped sets is O(k) and sorting their union is O(k log k), with no dependence on n beyond two subtractions. Space O(k). The scan over every index costs O(n) time for the same O(k) output, and concatenating the two ranges brings the best case down to O(k).
Edge cases to test
kv_keep(5, 2, 3)→[0, 1, 2, 3, 4]. The ranges meet exactly, so nothing is evicted.kv_keep(6, 4, 4)→[0, 1, 2, 3, 4, 5]. Indices 2 and 3 are in both ranges; a list concatenation returns them twice.kv_keep(3, 10, 10)→[0, 1, 2]. Unclamped,range(3 - 10, 3)yields -7 to -1, and Python lists accept negative indices silently, so a lookup reads the wrong token instead of failing.kv_keep(4, 0, 2)→[2, 3]. No sinks is plain sliding-window attention, the setup StreamingLLM showed degrading once the first tokens leave the cache.kv_keep(10, 2, 0)→[0, 1]. A zero window keeps only the sinks, becauserange(10, 10)is empty.kv_keep(0, 4, 8)→[]. An empty sequence keeps nothing.
Common mistakes
- Concatenating the two ranges without deduplicating — when
sink + windowexceedsnthey overlap and indices appear twice. - Not clamping:
range(n - window, n)starts at a negative index whenwindow > n, andrange(sink)invents tokens past the end whensink > n. - Off-by-one on the window start: the last
windowtokens begin atn - window, notn - window + 1. - Dropping the sinks to save a few slots — a window-only cache is the configuration StreamingLLM showed degrading once the first tokens are evicted.
- In TypeScript, sorting numbers with the default comparator:
[10, 9].sort()compares strings and leaves[10, 9].
Follow-ups an interviewer asks next
- Tokens arrive one at a time. Maintain the cache incrementally.
- Keep the sinks fixed and hold the window in a ring buffer or deque of capacity
window. Each new token is appended; once the cache holdssink + windowtokens, the oldest window entry, indext - windowwhen tokentarrives, is evicted. Each step is O(1), and no step recomputes the whole set. - What positions does the model see for the kept tokens?
- StreamingLLM assigns positions by place in the cache, not in the original text: with sinks 0 and 1 and window 7 to 9, the model sees positions 0 to 4. With rotary position embeddings that means caching keys before the rotation and applying it at each decoding step. Using the original indices would push positions past the lengths the model was trained on as the stream grows.
- Size the window from a memory budget in bytes.
- Each cached token stores one key and one value per layer, so it costs
2 × layers × kv_heads × head_dim × bytes_per_value. Divide the budget by that, subtract the sinks, and the rest is the window. Grouped-query attention reduceskv_headsand a lower-precision cache reducesbytes_per_value, which is why both stretch the window within the same memory. - Can you keep important middle tokens instead of dropping all of them?
- Yes, and that is the next family of policies. Heavy-hitter methods such as H2O keep the tokens that have accumulated the most attention so far, alongside the recent window. They need per-token attention statistics, so they cost more bookkeeping than a fixed sinks-plus-window rule, and they still cannot bring back a token once it has been evicted.
Where this shows up
The KV cache is the memory bottleneck of LLM serving: every generated token adds a key and a value per layer, so a long chat or a streaming agent eventually runs out of GPU memory. A sinks-plus-window policy, from the StreamingLLM paper, caps that memory at a fixed number of tokens while keeping generation stable, which suits always-on assistants and long agent sessions. It trades recall of the middle of a conversation for bounded memory, so it extends how long a model can run, not how much it remembers.
Two practical details decide how the policy behaves. The StreamingLLM paper found four initial tokens were generally enough as sinks, and that a model pre-trained with a dedicated placeholder token at the start of every sequence could rely on that single token instead. And the policy changes what a long session can rely on: only those first few tokens are pinned, so the rest of a long system prompt slides out of the window like any other text. Instructions or facts from early in a session that must keep working have to be restated or retrieved back into the window; the window bounds memory, it does not replace it.
Check yourself
Predict kv_keep(12, 4, 5).
[0, 1, 2, 3, 7, 8, 9, 10, 11]. The sinks are 0 to 3 and the window starts at 12 − 5 = 7, so tokens 4, 5 and 6 are the only ones evicted.
A bug starts the window at n - window + 1. What does kv_keep(10, 2, 3) return, and what is wrong with it?
[0, 1, 8, 9]. range(n - window + 1, n) holds only window - 1 indices, so the cache silently runs one token short of its budget and drops token 7, which should still be in the window.
A stream reaches n = 100000 with sink = 4 and window = 1020. How many tokens are cached, and which is the oldest non-sink token kept?
1,024 tokens are cached and 98,976 have been evicted. The window starts at 100,000 − 1,020 = 98,980, so the list is 0 to 3 followed by 98,980 to 99,999. The cache size depends only on the two budgets, never on n.
A model has 32 layers, 8 KV heads, head dimension 128 and 2-byte cache values. How much memory does that 1,024-token cache take, and what would a full cache of a million tokens take?
Each token costs 2 × 32 × 8 × 128 × 2 = 131,072 bytes, 128 KiB, so 1,024 tokens take 128 MiB. A full cache grows linearly: a million tokens would take about 122 GiB, far beyond one GPU, while the sinks-plus-window cache stays at 128 MiB.
Reference solution
Reference solution — Python
def kv_keep(n, sink, window):
sinks = set(range(min(sink, n))) # first tokens (attention sinks)
recent = set(range(max(0, n - window), n)) # most recent tokens
return sorted(sinks | recent) # union, sorted
print(kv_keep(10, 2, 3)) # -> [0, 1, 7, 8, 9]
print(kv_keep(5, 2, 3)) # -> [0, 1, 2, 3, 4]Reference solution — TypeScript
function kvKeep(n: number, sink: number, window: number): number[] {
const keep = new Set<number>();
for (let i = 0; i < Math.min(sink, n); i++) keep.add(i); // attention sinks
for (let i = Math.max(0, n - window); i < n; i++) keep.add(i); // recent window
return Array.from(keep).sort((a, b) => a - b);
}
console.log(kvKeep(10, 2, 3)); // -> [0, 1, 7, 8, 9]
console.log(kvKeep(5, 2, 3)); // -> [0, 1, 2, 3, 4]Questions about KV-Cache Eviction (Attention Sinks)
What is an attention sink in a language model?
An attention sink is a token, usually one of the first in the sequence, that receives a large share of attention from later tokens regardless of its content. The StreamingLLM authors observed it across model families such as Llama 2 and tied it to softmax: attention weights must sum to 1, so when a query matches nothing strongly the leftover weight has to land somewhere, and the initial tokens, which every later position can see, collect it. Evicting those tokens changes the attention distribution, which is why window attention that drops them degrades.
How does StreamingLLM keep the KV cache bounded?
It keeps two groups of cached keys and values: a few initial tokens that act as attention sinks, and a rolling window of the most recent tokens. Everything in between is evicted as the stream grows, so the cache stays at sink plus window tokens and memory and per-token attention cost stop growing with length. The trade-off is that evicted tokens are gone. The model cannot recall details from the middle of a long conversation, so the method extends how long a model can keep generating, not how much context it can use.
Why not just keep a sliding window of the most recent tokens?
Because plain window attention breaks down once the first tokens fall out of the window. In the StreamingLLM experiments quality degraded sharply at that point, since those early tokens had been absorbing attention as sinks. Keeping a handful of them costs a few cache slots out of thousands and kept generation stable over very long streams. The accurate alternative, recomputing attention over the recent window from scratch for every new token, avoids the problem but is far slower, because it redoes the whole window each step.
How do you compute which tokens survive sink plus window eviction?
Take the union of two ranges: indices from 0 up to sink minus 1, clamped to the sequence length, and the last window indices, starting at the larger of 0 and n minus window. Use a set, or merge the two sorted ranges, so an index covered by both appears once, and return the result in order. For n = 10, sink = 2 and window = 3 the survivors are 0, 1, 7, 8 and 9, and tokens 2 through 6 are evicted. When sink or window exceeds n, the answer is every index from 0 to n minus 1.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Challenges
- SoftmaxThe function at the end of every classifier and language model: turn raw scores (logits) into a probability distribution. Implement the numerically stable version so big logits do not overflow. Solve it in Python or TypeScript.Read →
- Single-Head AttentionThe operation at the heart of every Transformer: scaled dot-product attention. Given queries, keys, and values, let each query pull a weighted blend of the values — softmax(QKᵀ/√d)·V — with a numerically stable softmax and no numpy, just the math. Solve it in Python or TypeScript.Read →
- Layer NormalizationThe stabilizer wrapped around every Transformer sub-layer: re-center and re-scale a vector to mean 0 and variance 1, then let learned gamma and beta stretch and shift it back — y = gamma·(x−mean)/√(var+eps) + beta. Keeps deep nets trainable. Solve it in Python or TypeScript.Read →
- Cross-Entropy LossThe loss that trains almost every classifier and language model. It measures how surprised the model was by the right answer — high probability on the true class → near 0, confidently wrong → explodes. Return -log(p[target]), eps-guarded. Solve it in Python or TypeScript.Read →
- TF-IDFThe scoring that ran search for decades — and still seeds hybrid retrieval today. Reward a word frequent in one document but rare across the corpus, shrug off words that appear everywhere: tf·log(N/df). Solve it in Python or TypeScript.Read →
- LRU CacheThe eviction policy behind every size-limited cache: when you run out of room, throw out whatever was used least recently. The trick is O(1) get and put — an ordered hash map (Python dict / JS Map) gives you exactly that. Solve it in Python or TypeScript.Read →