SGLang Prefix KV Cache and Leaf-Only LRU
SGLang · NeurIPS 2024 · Hard · 40 minutes
Find the longest cached prefix and evict only unpinned leaves under a capacity limit.
A token-node expansion of radix-tree semantics modeling shared prefixes, LRU and active-request pins, without storing actual KV tensors.
Functions to implement
radix_cache_step(cache: dict, prompt: tuple[int, ...], capacity: int, clock: int, pinned: tuple = ()) -> tuple[dict, int]
SGLang Prefix KV Cache and Leaf-Only LRU
1. Problem
Find the longest cached prefix and evict only unpinned leaves under a capacity limit.
A token-node expansion of radix-tree semantics modeling shared prefixes, LRU and active-request pins, without storing actual KV tensors.
Source: SGLang: Efficient Execution of Structured Language Model Programs · Section 3: RadixAttention, longest-prefix reuse, leaf-first LRU and reference counters.
2. Core equations
$$ h(x)=\max{j:x_{:j}\in C},\qquad e=\arg\min_{p\in\operatorname{leaves}(C)\setminus P}(\operatorname{lastUse}(p),p). $$
3. From equations to code
radix_cache_step(cache: dict, prompt: tuple[int, ...], capacity: int, clock: int, pinned: tuple = ()) -> tuple[dict, int]— Copied cache after prefix reuse/insertion/eviction, and matched prefix length.
Match consecutive tokens from the root, never arbitrary suffixes. Copy the cache and update timestamps. When full, remove the oldest unprotected node with no children; an ancestor becomes evictable only after its children disappear.
4. Conventions
cache maps nonempty token tuples to integer last-use times and must be prefix-closed. prompt is a nonempty tuple of nonnegative ints; capacity counts nonroot token nodes. clock is at least existing timestamps. pinned names cached nodes whose ancestors are also protected. Protect the current prompt path too; break LRU ties lexicographically by token tuple. Return (new_cache, reused_tokens), never mutating input even on failure.
5. Experiment view
Replay six prompts sharing system prefixes with capacities seven and twelve; compare prefill token counts with no caching and verify node capacity.
The chart is generated by the actual submitted kernel during T3 and by the reference during export. Values are synthetic teaching measurements, not GPU throughput or full-model quality claims.
6. Run your implementation
Complete the functions in the Python editor on the right, then click Run tests. Inspect each failed check, update your implementation, and run again. Passing every required check marks the problem as solved and unlocks the notes.
7. Further study
Read the cited section and explain which dimensions or scheduling constraints the kernel preserves. Then extend the experiment beyond the stated fixture while retaining the existing contract. Larger models, real devices, and communication costs require separate measurement.