Skip to content

Commit 20518d8

Browse files
authored
[Scheduler] Align RadixCache no-insert cleanup with kv_len_to_handle (#35204)
1 parent 7bc9152 commit 20518d8

2 files changed

Lines changed: 56 additions & 35 deletions

File tree

‎python/sglang/srt/mem_cache/radix_cache.py‎

Lines changed: 42 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,19 @@ def cache_finished_req(
494494
)
495495
return
496496

497+
if not is_insert:
498+
# Frees committed slots that no token id names, which the insert
499+
# path below cannot reach; the protected prefix stays with the cache.
500+
kv_indices = self.req_to_token_pool.req_to_token[
501+
req.kv.req_pool_idx, req.kv.cache_protected_len : kv_len_to_handle
502+
]
503+
self.token_to_kv_pool_allocator.free_segment(
504+
kv_indices, start_pos=req.kv.cache_protected_len
505+
)
506+
if req.last_node is not None:
507+
self.dec_lock_ref(req.last_node)
508+
return
509+
497510
token_ids = (req.origin_input_ids + req.output_ids)[:kv_len_to_handle]
498511
kv_indices = self.req_to_token_pool.req_to_token[
499512
req.kv.req_pool_idx, : len(token_ids)
@@ -509,39 +522,36 @@ def cache_finished_req(
509522
values = kv_indices[:key_len].to(dtype=torch.int64, copy=True)
510523

511524
# Radix Cache takes one ref in memory pool
512-
if is_insert:
513-
priority = getattr(req, "priority", 0) or 0
514-
result = self.insert(
515-
InsertParams(key=radix_key, value=values, priority=priority)
516-
)
517-
# A request that was never cached while unfinished can add its
518-
# whole prompt and generated output as one leaf. Split that leaf at
519-
# the prompt boundary so LRU eviction can discard output KV without
520-
# also losing the reusable prompt KV. Reinserting a prefix only
521-
# changes radix topology; it reuses the indices inserted above.
522-
prompt_key = RadixKey(
523-
token_ids[: len(req.origin_input_ids)],
524-
req.extra_key,
525-
is_bigram=self.is_eagle,
526-
cache_salt=req.cache_salt,
527-
).page_aligned(self.page_size)
528-
if 0 < len(prompt_key) < key_len:
529-
self.insert(
530-
InsertParams(
531-
key=prompt_key,
532-
value=values[: len(prompt_key)],
533-
priority=priority + 1,
534-
# Topology-only re-insert: this request created these
535-
# nodes moments ago, so counting it as a hit is the
536-
# same self-referencing inflation `chunked` exists to
537-
# suppress. hit_count drives eviction order, so an
538-
# extra bump would silently promote every prompt node.
539-
chunked=True,
540-
)
525+
priority = getattr(req, "priority", 0) or 0
526+
result = self.insert(
527+
InsertParams(key=radix_key, value=values, priority=priority)
528+
)
529+
# A request that was never cached while unfinished can add its
530+
# whole prompt and generated output as one leaf. Split that leaf at
531+
# the prompt boundary so LRU eviction can discard output KV without
532+
# also losing the reusable prompt KV. Reinserting a prefix only
533+
# changes radix topology; it reuses the indices inserted above.
534+
prompt_key = RadixKey(
535+
token_ids[: len(req.origin_input_ids)],
536+
req.extra_key,
537+
is_bigram=self.is_eagle,
538+
cache_salt=req.cache_salt,
539+
).page_aligned(self.page_size)
540+
if 0 < len(prompt_key) < key_len:
541+
self.insert(
542+
InsertParams(
543+
key=prompt_key,
544+
value=values[: len(prompt_key)],
545+
priority=priority + 1,
546+
# Topology-only re-insert: this request created these
547+
# nodes moments ago, so counting it as a hit is the
548+
# same self-referencing inflation `chunked` exists to
549+
# suppress. hit_count drives eviction order, so an
550+
# extra bump would silently promote every prompt node.
551+
chunked=True,
541552
)
542-
freed_end = result.prefix_len
543-
else:
544-
freed_end = key_len
553+
)
554+
freed_end = result.prefix_len
545555

546556
# duplicates / uninserted range, then the unaligned tail
547557
self.token_to_kv_pool_allocator.free_segments(

‎test/registered/unit/mem_cache/test_decode_radix_lock_ref.py‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
from sglang.srt.mem_cache.radix_cache import RadixCache, RadixKey
4848
from sglang.srt.mem_cache.unified_cache.component_type import ComponentType
4949
from sglang.srt.utils.common import Range
50+
from sglang.test.test_utils import CustomTestCase
5051

5152

5253
def _make_cache_with_pools(page_size=1):
@@ -104,7 +105,7 @@ def _make_req(fill_ids, req_pool_idx=0, cache_protected_len=0, last_node=None):
104105
return MockReq(fill_ids, req_pool_idx, cache_protected_len, last_node)
105106

106107

107-
class TestDecodeLockRefScenarios(unittest.TestCase):
108+
class TestDecodeLockRefScenarios(CustomTestCase):
108109
def setUp(self):
109110
# The decode queue reads its config from the bags.
110111
reset_context()
@@ -290,7 +291,10 @@ def test_full_transfer_success(self):
290291
self.assertEqual(cache.evictable_size(), len(full_ids))
291292

292293
def test_incremental_transfer_failure(self):
293-
"""Scenario 3: prefix match > 0, transfer fails.
294+
"""Scenario 3: prefix match > 0, transfer fails after KV commit.
295+
296+
The final committed KV slot has no corresponding output token. Cleanup
297+
must preserve the matched prefix and release the full request-owned suffix.
294298
295299
Flow: inc_lock_ref(pop_preallocated)
296300
-> dec_lock_ref(cache_finished_req via release_kv_cache is_insert=False)
@@ -322,13 +326,20 @@ def test_incremental_transfer_failure(self):
322326
cache_protected_len=prefix_len,
323327
last_node=matched_node,
324328
)
329+
req.output_ids = array("q")
325330

326331
# Transfer fails -> cache_finished_req with is_insert=False
327-
# This frees delta tokens and dec_lock_ref on last_node
332+
cache.token_to_kv_pool_allocator.reset_mock()
328333
cache.cache_finished_req(
329334
req, is_insert=False, kv_len_to_handle=req.kv.kv_committed_len
330335
)
331336

337+
free_call = cache.token_to_kv_pool_allocator.free_segment.call_args
338+
torch.testing.assert_close(
339+
free_call.args[0], torch.tensor(full_vals[prefix_len:])
340+
)
341+
self.assertEqual(free_call.kwargs["start_pos"], prefix_len)
342+
332343
# The prefix node should be unlocked (back to evictable)
333344
self.assertEqual(cache.root_node.lock_ref, 1)
334345
self.assertEqual(cache.protected_size(), 0)

0 commit comments

Comments
 (0)