From 80c54e6ac52c769cb66c4bda53942898965e9bc3 Mon Sep 17 00:00:00 2001 From: ormandj Date: Fri, 16 Oct 2026 12:45:16 -0500 Subject: [PATCH] [Fix] [AMD] hicache: Serve encoder-replay prefix hits with a paged DSpark draft SWA (#42716) Co-authored-by: hnyls2002 --- .../sglang/srt/mem_cache/cache_init_params.py | 3 + .../sglang/srt/mem_cache/kv_cache_builder.py | 12 ++++ .../srt/mem_cache/rust_tree_core/adapter.py | 3 +- .../mem_cache/unified_cache/components/swa.py | 9 +-- .../test_rust_tree_core_integration.py | 68 ++++++++++++++++++- .../mem_cache/test_unified_cache_linker.py | 1 + 6 files changed, 85 insertions(+), 11 deletions(-) diff --git a/python/sglang/srt/mem_cache/cache_init_params.py b/python/sglang/srt/mem_cache/cache_init_params.py index 0ccb947aff..af56ae0543 100644 --- a/python/sglang/srt/mem_cache/cache_init_params.py +++ b/python/sglang/srt/mem_cache/cache_init_params.py @@ -54,6 +54,9 @@ class CacheInitParams: chunked_prefill_size: Optional[int] = None sliding_window_size: Optional[int] = None + # False when tree nodes do not own the SWA state (a per-request SWA ring, or a + # paged SWA pool only a draft uses), so it must not gate prefix matching. + swa_gates_prefix_match: bool = True decoder_swa_bounded_replay: bool = False # Time-to-live for cache entries in seconds. If None, TTL is disabled. diff --git a/python/sglang/srt/mem_cache/kv_cache_builder.py b/python/sglang/srt/mem_cache/kv_cache_builder.py index d0a6902c56..c4e26ea4d4 100644 --- a/python/sglang/srt/mem_cache/kv_cache_builder.py +++ b/python/sglang/srt/mem_cache/kv_cache_builder.py @@ -37,6 +37,7 @@ from sglang.srt.configs.hybrid_arch import ( from sglang.srt.configs.model_config import ModelImpl, is_deepseek_dsa from sglang.srt.environ import envs from sglang.srt.managers.mm_schedule import init_mm_embedding_cache +from sglang.srt.mem_cache.allocator.swa import is_swa_req_ring from sglang.srt.mem_cache.base_swa_memory_pool import BaseSWAKVPool from sglang.srt.mem_cache.cache_init_params import CacheInitParams from sglang.srt.mem_cache.deepseek_v4_memory_pool import DeepSeekV4TokenToKVPool @@ -326,6 +327,16 @@ def build_kv_cache( req_to_token_pool, token_to_kv_pool_allocator = tp_worker.get_memory_pool() mtp_draft_device_pools = tp_worker.model_runner.mtp_draft_device_pools + # SWA the tree does not own must not gate prefix matching: a per-request ring, + # or paged SWA beside the target's encoder-replay request window, which then + # only the draft uses. + swa_gates_prefix_match = not ( + is_swa_req_ring(token_to_kv_pool_allocator) + or ( + isinstance(token_to_kv_pool, DeepSeekV4TokenToKVPool) + and token_to_kv_pool.request_window is not None + ) + ) retraction_backup = resolve_decode_retraction_backup(tp_worker=tp_worker) @@ -386,6 +397,7 @@ def build_kv_cache( attn_cp_size=parallel.attn_cp_size, chunked_prefill_size=effective_chunked_prefill_size, sliding_window_size=sliding_window_size, + swa_gates_prefix_match=swa_gates_prefix_match, mtp_draft_device_pools=mtp_draft_device_pools, mtp_draft_mamba_pools=tp_worker.model_runner.mtp_draft_mamba_pools, ) diff --git a/python/sglang/srt/mem_cache/rust_tree_core/adapter.py b/python/sglang/srt/mem_cache/rust_tree_core/adapter.py index e07d7ec339..8902700587 100644 --- a/python/sglang/srt/mem_cache/rust_tree_core/adapter.py +++ b/python/sglang/srt/mem_cache/rust_tree_core/adapter.py @@ -18,7 +18,6 @@ from sglang.srt.disaggregation.kv_events import ( namespaced_block_hash, ) from sglang.srt.environ import envs -from sglang.srt.mem_cache.allocator.swa import is_swa_req_ring from sglang.srt.mem_cache.base_prefix_cache import ( DecLockRefParams, DecLockRefResult, @@ -470,7 +469,7 @@ class RustUnifiedTreeCore(UnifiedTreeCoreInterface): write_through_threshold=256, device=str(self.device), swa_sliding_window_size=params.sliding_window_size, - swa_req_ring=is_swa_req_ring(self._allocator), + swa_req_ring=not params.swa_gates_prefix_match, enable_kv_cache_events=params.enable_kv_cache_events, dynamo_kv_event_format=params.dynamo_kv_event_format, mamba_cache_chunk_size=( diff --git a/python/sglang/srt/mem_cache/unified_cache/components/swa.py b/python/sglang/srt/mem_cache/unified_cache/components/swa.py index 1612b74cc9..f835bba12a 100644 --- a/python/sglang/srt/mem_cache/unified_cache/components/swa.py +++ b/python/sglang/srt/mem_cache/unified_cache/components/swa.py @@ -5,7 +5,6 @@ from typing import TYPE_CHECKING, Callable, Optional, Sequence import torch from sglang.srt.environ import envs -from sglang.srt.mem_cache.allocator.swa import is_swa_req_ring from sglang.srt.mem_cache.base_prefix_cache import ( DecLockRefParams, EvictParams, @@ -90,6 +89,7 @@ class SWAComponent(TreeComponent): super().__init__(cache, params) self._session_leaf_covered_len: dict[str, dict[UnifiedTreeNode, int]] = {} self.sliding_window_size = params.sliding_window_size + self.gates_prefix_match = params.swa_gates_prefix_match self.full_window_pages = ( self.sliding_window_size + params.page_size - 1 ) // params.page_size @@ -358,10 +358,7 @@ class SWAComponent(TreeComponent): sliding_window_size = self.sliding_window_size ct = self.component_type state = {"len": float("inf")} - - # A per-request SWA ring is not stored in tree nodes, so its bookkeeping - # must not gate prefix matching. - swa_req_ring = is_swa_req_ring(self.cache.token_to_kv_pool_allocator) + gates_prefix_match = self.gates_prefix_match def validator(node: UnifiedTreeNode) -> bool: cd = node.component_data[ct] @@ -369,7 +366,7 @@ class SWAComponent(TreeComponent): # — load_back will restore SWA from host before use. if cd.value is None and (match_device_only or cd.host_value is None): state["len"] = 0 - if swa_req_ring and (node.backuped or not node.evicted): + if not gates_prefix_match and (node.backuped or not node.evicted): return True return False state["len"] += len(node.key) diff --git a/test/registered/unit/mem_cache/test_rust_tree_core_integration.py b/test/registered/unit/mem_cache/test_rust_tree_core_integration.py index 0afe96cbf8..944bddc302 100644 --- a/test/registered/unit/mem_cache/test_rust_tree_core_integration.py +++ b/test/registered/unit/mem_cache/test_rust_tree_core_integration.py @@ -2190,7 +2190,14 @@ def _swa_tree_core(window: int = 8, **params_overrides) -> RustUnifiedTreeCore: def _swa_transfer_core( - backend, unified=False, mamba=False, page_size=1, window=16, is_eagle=False + backend, + unified=False, + mamba=False, + page_size=1, + window=16, + is_eagle=False, + request_window=False, + has_swa_host_pool=True, ): from sglang.srt.mem_cache.allocator.swa import SWATokenToKVPoolAllocator from sglang.srt.mem_cache.allocator.unified_hybrid_swa import ( @@ -2216,6 +2223,7 @@ def _swa_transfer_core( tree_components=(ComponentType.FULL, ComponentType.SWA) + ((ComponentType.MAMBA,) if mamba else ()), sliding_window_size=window, + swa_gates_prefix_match=not request_window, ) with get_context().override_server_args( _mamba_cache_chunk_size=256, mamba_max_states_per_path=-1 @@ -2235,7 +2243,7 @@ def _swa_transfer_core( core = UnifiedTreeCore(params, components) cache.tree_core = core core.set_hicache_enabled() - core.has_swa_host_pool = True + core.has_swa_host_pool = has_swa_host_pool return core, allocator @@ -2615,7 +2623,13 @@ def test_write_back_load_back_ignores_auxiliary_nodes_for_pending_ownership(): core.sanity_check([], []) -def _swa_cache(window: int = 8, page_size: int = 1, backend="rust", ring=False): +def _swa_cache( + window: int = 8, + page_size: int = 1, + backend="rust", + ring=False, + request_window=False, +): """A real UnifiedRadixCache and SWA allocator, defaulting to the Rust core.""" from sglang.srt.mem_cache.allocator.swa import SWATokenToKVPoolAllocator from sglang.srt.mem_cache.memory_pool import ReqToTokenPool @@ -2642,6 +2656,9 @@ def _swa_cache(window: int = 8, page_size: int = 1, backend="rust", ring=False): ) if ring: kv_pool.swa_req_ring_size = window + if request_window: + # Stand-in for DeepSeek-V4.1's encoder-replay request window. + kv_pool.request_window = object() allocator = SWATokenToKVPoolAllocator( size=64, size_swa=64, @@ -2660,6 +2677,7 @@ def _swa_cache(window: int = 8, page_size: int = 1, backend="rust", ring=False): page_size=page_size, disable=False, sliding_window_size=window, + swa_gates_prefix_match=not (ring or request_window), tree_components=(ComponentType.FULL, ComponentType.SWA), ) ) @@ -3999,6 +4017,50 @@ def test_swa_match_uses_allocator_layout(backend, ring, hicache, has_swa_host_po ) +@pytest.mark.parametrize("backend", ["python", "rust"]) +@pytest.mark.parametrize("hicache", [False, True]) +def test_swa_match_ignores_tombstones_with_a_request_window(backend, hicache): + # Encoder SWA replay keeps SWA in a per-request window and rebuilds it on a + # hit, so an SWA tombstone must not cut the Full-KV match short. + cache, allocator = _swa_cache(backend=backend, request_window=True) + indices = allocator.alloc(12) + cache.insert( + InsertParams( + key=_key(list(range(12))), + value=indices, + component_evicted_seqlens={ComponentType.SWA: 8}, + ) + ) + if hicache: + cache.tree_core.set_hicache_enabled() + matched = cache.match_prefix(MatchPrefixParams(key=_key(list(range(8))))) + assert matched.full_kv_hit_length == 8 + assert matched.device_prefix_len == 8 + assert ( + cache.path_device_indices(matched.last_device_node)[:8].tolist() + == indices[:8].tolist() + ) + + +@pytest.mark.parametrize("backend", ["python", "rust"]) +@pytest.mark.parametrize("request_window", [False, True]) +def test_swa_host_only_prefix_matches_with_a_request_window(backend, request_window): + # Without an SWA host pool, a prefix demoted to host keeps no SWA value. + # Replay rebuilds a request window, so the prefix stays a host hit; paged + # SWA still requires resident SWA state. + core, _ = _swa_transfer_core( + backend, request_window=request_window, has_swa_host_pool=False + ) + leaf = _insert(core, list(range(8)), list(range(10, 18))).last_device_node + core.commit_backup(leaf, torch.arange(100, 108), {}) + core.mark_write_through_pending([leaf], leaf) + core.finish_write_through([leaf], leaf) + _accumulate_step(core.demote(leaf), {}, {}, {}) + assert core.component_has_host_value_only(leaf, ComponentType.FULL) + matched = core.match_prefix(MatchPrefixParams(key=_key(list(range(8))))) + assert matched.host_hit_length == (8 if request_window else 0) + + def test_buffer_backup_snapshot_round_trips_and_detects_a_split(): core = _tree_core() core.enable_storage = True diff --git a/test/registered/unit/mem_cache/test_unified_cache_linker.py b/test/registered/unit/mem_cache/test_unified_cache_linker.py index 7e35c86589..fc6703713e 100644 --- a/test/registered/unit/mem_cache/test_unified_cache_linker.py +++ b/test/registered/unit/mem_cache/test_unified_cache_linker.py @@ -1143,6 +1143,7 @@ def test_swa_reuse_policy_tracks_layout_without_a_tier_condition( monkeypatch.setattr(env_gate, "is_unified_kv_triton", lambda: unified_kv) component = SWAComponent.__new__(SWAComponent) component.sliding_window_size = 128 + component.gates_prefix_match = not unified_kv cache = UnifiedRadixCache.__new__(UnifiedRadixCache) cache.token_to_kv_pool_allocator = _swa_allocator(swa_req_ring) cache.components = {ComponentType.SWA: component}