Choose which positions stay in an attention-sink streaming cache

Why it matters Streaming chat and long-running agents use sink-plus-window caches to generate indefinitely with fixed memory.

Streaming generation with a fixed-size cache works much better if the first few tokens (attention sinks) are kept forever alongside a recent window.

Write sink_keep(n_tokens, n_sink, window). Positions are 0..n_tokens-1. Keep the first n_sink positions and the last window positions. Return the sorted list of kept positions without duplicates. If n_tokens <= n_sink + window, every position is kept.

Signaturedef sink_keep(n_tokens, n_sink, window)

Example

sink_keep(10, 2, 3) is [0, 1, 7, 8, 9].

Understand the idea

A sliding window cache keeps only the most recent tokens, which sounds natural, but models trained with full attention dump a lot of attention weight on the very first tokens. Evict those and the softmax has nowhere to put that weight, and quality collapses. Keeping a few early tokens as permanent "sinks" fixes it, like keeping an anchor while the boat drifts.

Example: 10 tokens so far, 2 sinks, window 3. Keep 0 and 1 forever, plus the newest three: 7, 8, 9. When token 10 arrives, 7 is evicted and the cache becomes 0, 1, 8, 9, 10.

Rule: kept = [0 .. n_sink-1] + [n - window .. n-1], or all positions if n <= n_sink + window.

This is the idea behind attention-sink streaming (StreamingLLM). The cache size stays n_sink + window no matter how long generation runs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplesink_keep(10, 2, 3)
  • Sample 2: short streamsink_keep(4, 2, 3)
  • Test 3: exact fitsink_keep(5, 2, 3)
  • Test 4: one sinksink_keep(100, 1, 4)