From 24624ad352398ffb4d7bfc5e5a4b8be7e80c5101 Mon Sep 17 00:00:00 2001 From: HowardYangAI <13777842855@163.com> Date: Tue, 24 Nov 2026 21:55:23 +0800 Subject: [PATCH] fix(core): evict prefix chain tails so leading pages stay reusable Prefix keys are chained: a page's key is computed from every page before it, so a lookup walks from the first page and stops at the first gap. Eviction picked the least recently used entry, and the first page is the one published earliest, so it went first and left every page behind it cached but impossible to find. Each entry now records which page comes before it and how many follow, and eviction takes the entry that has gone unused the longest with nothing chained after it. Tails are queued by their own use time, so a hit refreshes the pages it reached and eviction no longer rescans the cache for every page it drops. Queued records that a later hit or a new successor replaces are pruned once they outnumber the cache. Caching a 35-token prompt and letting a second prompt fill the cache, a re-request reused nothing before and now reuses 6, 16 and 32 tokens in 90-, 110- and 140-page pools. --- tests/test_prefix_growth.py | 131 ++++++++++++++++++++++++++++++ vllm_rlt/core/kv_cache_manager.py | 70 +++++++++++++++- 2 files changed, 199 insertions(+), 2 deletions(-) diff --git a/tests/test_prefix_growth.py b/tests/test_prefix_growth.py index 9fe717c6..aa99b5af 100644 --- a/tests/test_prefix_growth.py +++ b/tests/test_prefix_growth.py @@ -66,6 +66,137 @@ def test_prefix_refcounts_and_eviction(): assert c.num_free_blocks == 12 +def test_eviction_takes_chain_tails_and_keeps_leading_pages(): + # Pages chain: a page is reachable only while every earlier page is cached. + # Evicting a chain head would strand its successors, so eviction has to + # take tails while still retiring the least recently used chain first. + c = KVCacheManager(1, 1, 4, 12, 2, 2, enable_prefix_caching=True) + old_prompt, new_prompt = [1, 2, 3, 4, 5], [7, 8, 9, 10, 11] + for name, prompt in (("old", old_prompt), ("new", new_prompt)): + assert c.allocate(name, 5) + c.mark_imported_prefix(name, 5) + c.publish_prefix(name, prompt, 5) + c.free(name) + assert len(c.lookup_prefix(old_prompt)) == len(c.lookup_prefix(new_prompt)) == 2 + # The older chain loses its tail first, so its head still serves a hit. + assert c.allocate("tail", 5) + assert len(c.lookup_prefix(old_prompt)) == 1 + assert len(c.lookup_prefix(new_prompt)) == 2 + c.free("tail") + # Only once the older chain is gone does the newer one lose its tail. + assert c.allocate("more", 9) + assert c.lookup_prefix(old_prompt) == () + assert len(c.lookup_prefix(new_prompt)) == 1 + c.free("more") + + +def test_draining_a_long_chain_does_not_rescan_the_cache(): + # Tails are queued by use time, so eviction takes one without repeatedly + # scanning the cache for entries that still have successors. + pages = 256 + c = KVCacheManager(1, 1, 4, 2 * pages + 16, 2, 2, enable_prefix_caching=True) + tokens = [(7 * i + 3) % 60 + 2 for i in range(pages * 2 + 2)] + assert c.allocate("publisher", len(tokens)) + c.mark_imported_prefix("publisher", len(tokens)) + c.publish_prefix("publisher", tokens, len(tokens)) + c.free("publisher") + entries = len(c._prefixes) + assert entries == pages + probes = 0 + counts = c._prefix_child_counts + + class Counting(dict): + def get(self, key, default=None): + nonlocal probes + probes += 1 + return dict.get(self, key, default) + + c._prefix_child_counts = Counting(counts) + while c._prefixes: + c._drop_refs(c._evict_prefix()) + # A scanning eviction would re-walk the cache for every page it drops. + assert probes <= 8 * entries + + +def test_repeated_hits_do_not_grow_the_eviction_queue(): + # Each hit queues a fresh eviction record; without pruning, the queue grows + # without bound on a cache whose contents never change. + c = KVCacheManager(1, 1, 4, 12, 2, 2, enable_prefix_caching=True) + prompt = [1, 2, 3, 4, 5] + assert c.allocate("publisher", 5) + c.mark_imported_prefix("publisher", 5) + c.publish_prefix("publisher", prompt, 5) + c.free("publisher") + for _ in range(2000): + assert len(c.lookup_prefix(prompt)) == 2 + assert len(c._prefix_leaves) <= 2 * len(c._prefixes) + 8 + # Pruning keeps the chain reachable: pressure still trims from the tail. + assert c.allocate("grower", 9) + assert len(c.lookup_prefix(prompt)) == 1 + c.free("grower") + + +def test_a_hit_leading_page_outlives_its_own_tail(): + # A hit reaches only the leading page, so the tail it leaves behind is the + # older record. Exposing that tail must not reset the leading page's use + # time, or eviction takes the page a request just reused. + hit, other = [1, 2, 3, 4, 5], [101, 102, 103, 104, 105] + c = KVCacheManager(1, 1, 4, 12, 2, 2, enable_prefix_caching=True) + for name, prompt in (("hit", hit), ("other", other)): + assert c.allocate(name, 5) + c.mark_imported_prefix(name, 5) + c.publish_prefix(name, prompt, 5) + c.free(name) + assert len(c.lookup_prefix(hit[:3])) == 1 + # Both chains lose their tail; neither leading page is retired. + assert c.allocate("grower", 7) + assert len(c.lookup_prefix(hit)) == 1 + assert len(c.lookup_prefix(other)) == 1 + c.free("grower") + + +def test_a_hit_chain_outlives_a_newer_one(): + # A hit refreshes every page it reached, and exposing a chain's tail must + # keep that tail's own use time. The hit chain is published first, so only + # correct ordering lets it survive while the newer chain is fully retired. + hit, newer = [1, 2, 3, 4, 5], [101, 102, 103, 104, 105] + c = KVCacheManager(1, 1, 4, 16, 2, 2, enable_prefix_caching=True) + for name, prompt in (("hit", hit), ("newer", newer)): + assert c.allocate(name, 5) + c.mark_imported_prefix(name, 5) + c.publish_prefix(name, prompt, 5) + c.free(name) + assert len(c.lookup_prefix(hit)) == 2 + # Pressure that must retire both newer pages before either hit page. + assert c.allocate("grower", 11) + assert len(c.lookup_prefix(hit)) == 2 + assert c.lookup_prefix(newer) == () + c.free("grower") + + +def test_evicted_chain_tail_still_serves_the_leading_prefix(): + e = LLMEngine( + model(), + cache_config=CacheConfig(90, 2, enable_prefix_caching=True, incremental_allocation=True), + scheduler_config=SchedulerConfig(prefill_chunk_size=4), + ) + p = SamplingParams(max_tokens=4, exit_threshold=0, ignore_eos=True) + cache = e.cache_manager + first = [(7 * i + 3) % 60 + 2 for i in range(35)] + second = [(11 * i + 41) % 60 + 2 for i in range(35)] + e.add_request("first", list(first), p) + cold = finish(e)["first"].token_ids + e.add_request("second", list(second), p) + finish(e) + # The second prompt evicted part of the first chain, not its head. + reachable = len(cache.lookup_prefix(first)) + assert 0 < reachable < 17 + hits = cache.prefix_hits + e.add_request("again", list(first), p) + assert finish(e)["again"].token_ids == cold + assert cache.prefix_hits == hits + reachable * cache.block_size + + def test_incremental_growth_matches_reserved_generation(): m = model() p = SamplingParams(max_tokens=9, exit_threshold=0, ignore_eos=True) diff --git a/vllm_rlt/core/kv_cache_manager.py b/vllm_rlt/core/kv_cache_manager.py index 77069894..8ce8a40c 100644 --- a/vllm_rlt/core/kv_cache_manager.py +++ b/vllm_rlt/core/kv_cache_manager.py @@ -11,6 +11,7 @@ """ import hashlib +import heapq import struct import weakref from collections import OrderedDict @@ -317,6 +318,16 @@ def __init__( self.watermark_blocks = int(watermark_ratio * num_blocks) if incremental_allocation else 0 self._refs = [0] * num_blocks self._prefixes = OrderedDict() + # Prefix keys chain: each page's digest covers every page before it, so + # a cached entry is reachable only while its ancestors are cached too. + self._prefix_parents = {} + self._prefix_child_counts = {} + # Chain tails, heapped by use time so eviction takes the oldest one + # without scanning the entries that have successors. Reuse and new + # successors leave stale heap entries, which eviction skips. + self._prefix_leaves = [] + self._prefix_used = {} + self._prefix_clock = 0 self._pending_prefixes = [] self.prefix_hits = self.prefix_queries = 0 if enable_prefix_caching and layout != "last_exited": @@ -374,8 +385,7 @@ def _claim(self, count): if len(self._free_blocks) < count and self.num_free_blocks < count: return None while len(self._free_blocks) < count and self._prefixes: - _, blocks = self._prefixes.popitem(last=False) - self._drop_refs(blocks) + self._drop_refs(self._evict_prefix()) if len(self._free_blocks) < count: return None blocks = [self._free_blocks.pop() for _ in range(count)] @@ -384,6 +394,54 @@ def _claim(self, count): self._refs[b] = 1 return blocks + def _touch_prefix(self, key): + """Record a publication or hit, queueing the entry while it is a tail.""" + self._prefix_clock += 1 + self._prefix_used[key] = self._prefix_clock + if not self._prefix_child_counts.get(key): + heapq.heappush(self._prefix_leaves, (self._prefix_clock, key)) + # Repeated hits supersede their own records; rebuild once they + # outnumber the cache instead of holding them until eviction. + if len(self._prefix_leaves) > 2 * len(self._prefixes) + 8: + self._prefix_leaves = [ + (used, cached) + for cached, used in self._prefix_used.items() + if not self._prefix_child_counts.get(cached) + ] + heapq.heapify(self._prefix_leaves) + + def _evict_prefix(self): + """Drop the least recently used entry that no cached entry extends. + + Evicting an entry strands every page chained behind it: lookup stops + at the first missing page, so those pages hold memory no request can + reuse. Taking a chain's tail keeps its leading pages reachable, and + each tail is evicted by its own use time. + """ + while self._prefix_leaves: + used, key = heapq.heappop(self._prefix_leaves) + # Reused or extended since it was queued; a current entry follows. + if self._prefix_used.get(key) != used or self._prefix_child_counts.get(key): + continue + return self._pop_prefix(key) + return self._pop_prefix(next(iter(self._prefixes))) + + def _pop_prefix(self, key): + """Remove one entry, re-queueing the tail its removal exposes.""" + blocks = self._prefixes.pop(key) + self._prefix_child_counts.pop(key, None) + self._prefix_used.pop(key, None) + parent = self._prefix_parents.pop(key, None) + if parent is not None: + remaining = self._prefix_child_counts.get(parent, 0) - 1 + if remaining > 0: + self._prefix_child_counts[parent] = remaining + else: + self._prefix_child_counts.pop(parent, None) + # The exposed tail keeps its own use time. + heapq.heappush(self._prefix_leaves, (self._prefix_used.get(parent, 0), parent)) + return blocks + def _prefix_keys(self, tokens): digest = b"" for start in range(0, len(tokens) // self.block_size * self.block_size, self.block_size): @@ -417,8 +475,10 @@ def publish_prefix(self, request_id, tokens, length, event=None): # Leave at least the last prompt token to recompute on a cache hit; # full-page alignment may leave additional tokens to recompute. publishable_tokens = min(length, len(tokens) - 1) + parent = None for index, key in enumerate(self._prefix_keys(tokens[:publishable_tokens])): if key in self._prefixes: + parent = key continue end = (index + 1) * self.block_size # Every depth and layer must have a contiguous written prefix. @@ -429,6 +489,11 @@ def publish_prefix(self, request_id, tokens, length, event=None): for b in blocks: self._refs[b] += 1 self._prefixes[key] = blocks + if parent is not None: + self._prefix_parents[key] = parent + self._prefix_child_counts[parent] = self._prefix_child_counts.get(parent, 0) + 1 + self._touch_prefix(key) + parent = key def lookup_prefix(self, tokens): if not self.enable_prefix_caching: @@ -440,6 +505,7 @@ def lookup_prefix(self, tokens): if blocks is None: break self._prefixes.move_to_end(key) + self._touch_prefix(key) found.append(blocks) return tuple(found)