diff --git a/python/sglang/srt/disaggregation/decode.py b/python/sglang/srt/disaggregation/decode.py index ee975a9b74b1..cd3ef17e0b8e 100644 --- a/python/sglang/srt/disaggregation/decode.py +++ b/python/sglang/srt/disaggregation/decode.py @@ -56,7 +56,7 @@ from sglang.srt.managers.schedule_policy import match_prefix_for_req from sglang.srt.managers.utils import GenerationBatchResult from sglang.srt.mem_cache.allocator import BaseTokenToKVPoolAllocator -from sglang.srt.mem_cache.base_prefix_cache import BasePrefixCache, EvictParams +from sglang.srt.mem_cache.base_prefix_cache import BasePrefixCache, EvictParams, InitLoadBackParams from sglang.srt.mem_cache.common import ( kv_to_page_indices, page_align_floor, @@ -248,6 +248,8 @@ class DecodeRequest: kv_receiver: CommonKVReceiver waiting_for_input: bool = False metadata_buffer_index: int = -1 + waiting_for_prefetch: bool = False + prefetch_triggered_time: float = 0.0 @property def seqlen(self) -> int: @@ -258,11 +260,31 @@ def priority(self) -> Optional[int]: return self.req.priority +@dataclass +class _PlannedPrealloc: + decode_req: DecodeRequest + prefix_indices: Optional[torch.Tensor] + prefix_len: int + required_alloc_tokens: int + origin_input_len: int + + +def _cleanup_hicache_aborted_request( + tree_cache: BasePrefixCache, enable_hicache: bool, req: Req +) -> None: + """Clean up HiRadixCache state for an aborted request.""" + if not enable_hicache: + return + tree_cache.release_aborted_request(req.rid) + + class DecodePreallocQueue: """ Store the requests that are preallocating. """ + _PREFETCH_WAIT_TIMEOUT: float = 5.0 + def __init__( self, req_to_token_pool: ReqToTokenPool, @@ -318,6 +340,7 @@ def __init__( "SGLANG_DISAGG_STAGING_BUFFER is designed for non-MLA models " "(e.g. GQA, MHA). MLA models should not set this flag." ) + self.enable_hicache = hasattr(tree_cache, "ongoing_prefetch") self.kv_manager = self._init_kv_manager() if self.enable_staging: self.transfer_queue._init_staging_handler(self.kv_manager) @@ -485,6 +508,134 @@ def _match_prefix_and_lock(self, req: Req) -> Tuple[torch.Tensor, int]: return prefix_indices, len(prefix_indices) + def _match_prefix(self, req: Req): + """Match prefix against radix cache (read-only, no GPU allocation, no lock).""" + return match_prefix_for_req( + self.tree_cache, + req, + req.origin_input_ids, + cow_mamba=self.tree_cache.supports_mamba(), + include_req=True, + ) + + def _load_back_and_lock( + self, + req: Req, + match_result, + extra_load_back_budget_consumed: int = 0, + skip_load_back: bool = False, + ) -> Tuple[torch.Tensor, int, int, int]: + """ + Optionally load matched host-cache prefix to GPU, then lock the + matched prefix node. + + When *skip_load_back* is True the L2->L1 transfer is skipped (e.g. + because a budget pre-check already determined the request cannot + fit), avoiding wasteful GPU-pool allocation and DMA. + + Returns: + (prefix_indices, prefix_len, load_back_tokens, lock_delta) + """ + prefix_indices = match_result.device_indices + last_device_node = match_result.last_device_node + last_host_node = match_result.last_host_node + host_hit_length = match_result.host_hit_length + load_back_tokens = 0 + + logger.debug( + "[HiCache][match_prefix] req=%s total_input=%d L1_gpu_hit=%d L2_host_hit=%d", + req.rid, + len(req.origin_input_ids), + len(prefix_indices), + host_hit_length, + ) + + if ( + not skip_load_back + and host_hit_length > 0 + and self.enable_hicache + ): + mem_quota = ( + self._allocatable_token_budgets(count_retracted=False) + - extra_load_back_budget_consumed + ) + load_result, new_last_node = self.tree_cache.init_load_back( + InitLoadBackParams( + best_match_node=last_host_node, + host_hit_length=host_hit_length, + mem_quota=mem_quota, + ) + ) + if len(load_result) > 0: + load_back_tokens = len(load_result) + prefix_indices = torch.cat([prefix_indices, load_result]) + last_device_node = new_last_node + req.last_node = new_last_node + + self.tree_cache.ready_to_load_host_cache() + + lock_delta = 0 + if len(prefix_indices) > 0: + lock_result = self.tree_cache.inc_lock_ref(last_device_node) + lock_delta = lock_result.delta + + return prefix_indices, len(prefix_indices), load_back_tokens, lock_delta + + def _unlock_prefix(self, req: Req, prefix_len: int) -> None: + """Undo inc_lock_ref from _load_back_and_lock when aborting or deferring.""" + if prefix_len > 0: + self.tree_cache.dec_lock_ref(req.last_node) + + def _trigger_prefetch_if_needed( + self, req: Req, last_host_node, prefix_len: int = 0 + ) -> None: + """Trigger prefetch from storage if HiRadixCache is enabled and storage backend is available.""" + if not self.enable_hicache: + return + if not self.tree_cache.enable_storage: + return + + matched_len = prefix_len + total_len = len(req.origin_input_ids) + + if matched_len >= total_len: + return + + suffix_tokens = req.origin_input_ids[matched_len:] + + if len(suffix_tokens) < self.tree_cache.prefetch_threshold: + return + + last_hash = None + prefix_keys = None + if last_host_node is not None: + last_hash = last_host_node.get_last_hash_value() + if self.tree_cache.hicache_storage_pass_prefix_keys: + prefix_keys = last_host_node.get_prefix_hash_values( + last_host_node.parent + ) + + self.tree_cache.prefetch_from_storage( + req_id=req.rid, + last_host_node=last_host_node, + new_input_tokens=suffix_tokens, + last_hash=last_hash, + prefix_keys=prefix_keys, + ) + + def _check_prefetch_progress( + self, rids_to_check: Optional[List[str]] = None + ) -> None: + """Check prefetch progress for ongoing prefetches and complete them.""" + if not self.enable_hicache: + return + + ongoing_prefetch_rids = list(self.tree_cache.ongoing_prefetch.keys()) + for rid in ongoing_prefetch_rids: + if rids_to_check is not None and rid not in rids_to_check: + continue + self.tree_cache.check_prefetch_progress(rid) + def _resolve_prefill_dp_rank(self, req: Req) -> Optional[int]: prefill_info = self.kv_manager.prefill_info_table.get(_bootstrap_addr(req)) # If None, it will go to the slow path and resolve prefill_info by _ensure_prefill_info then cache it @@ -528,6 +679,7 @@ def _check_if_req_exceed_kv_capacity(self, req: Req) -> bool: message = f"Request {req.rid} exceeds the maximum number of tokens: {len(req.origin_input_ids)} > {self.max_total_num_tokens}" logger.error(message) prepare_abort(req, message, status_code=HTTPStatus.BAD_REQUEST) + _cleanup_hicache_aborted_request(self.tree_cache, self.enable_hicache, req) self.scheduler.output_streamer.stream_output([req], req.return_logprob) return True if self._uses_swa_tail_prealloc(): @@ -637,6 +789,7 @@ def _update_handshake_waiters( error_message, status_code=HTTPStatus.INTERNAL_SERVER_ERROR, ) + _cleanup_hicache_aborted_request(self.tree_cache, self.enable_hicache, decode_req.req) if self.scheduler.metrics_reporter.enable_metrics: self.scheduler.metrics_collector.increment_bootstrap_failed_reqs() else: @@ -735,8 +888,16 @@ def pop_preallocated( self._resolve_pending_reqs() self._update_handshake_waiters(rids_to_check) + # Check HiRadixCache events (write completion, load completion, prefetch progress) + if self.enable_hicache: + self.tree_cache.check_hicache_events() + + # Check prefetch progress for ongoing prefetches + self._check_prefetch_progress(rids_to_check) + failed_reqs = [] preallocated_reqs = [] + planned_preallocs: List[_PlannedPrealloc] = [] indices_to_remove = set() # We need to make sure that the sum of inflight tokens and allocatable tokens is greater than maximum input+output length of each inflight request @@ -778,6 +939,7 @@ def pop_preallocated( if rids_to_check is not None and decode_req.req.rid not in rids_to_check: continue if isinstance(decode_req.req.finished_reason, FINISH_ABORT): + _cleanup_hicache_aborted_request(self.tree_cache, self.enable_hicache, decode_req.req) self.scheduler.output_streamer.stream_output( [decode_req.req], decode_req.req.return_logprob, @@ -801,6 +963,7 @@ def pop_preallocated( ) # Then, preallocate the remaining requests if possible + cumulative_load_back_tokens = 0 for i, decode_req in enumerate(self.queue): if rids_to_check is not None and decode_req.req.rid not in rids_to_check: continue @@ -811,6 +974,19 @@ def pop_preallocated( if not decode_req.waiting_for_input: continue + # Two-phase prefetch: check if request is waiting for L3->L2 prefetch + if decode_req.waiting_for_prefetch: + rid = decode_req.req.rid + prefetch_done = rid not in self.tree_cache.ongoing_prefetch + timed_out = ( + time.monotonic() - decode_req.prefetch_triggered_time + > self._PREFETCH_WAIT_TIMEOUT + ) + if prefetch_done or timed_out: + decode_req.waiting_for_prefetch = False + else: + continue + if self.req_to_token_pool.available_size() <= 0: break @@ -824,55 +1000,154 @@ def pop_preallocated( # TODO: add new_token ratio origin_input_len = len(decode_req.req.origin_input_ids) if self.scheduler.server_args.disaggregation_decode_enable_radix_cache: - # Match prefix against decode's radix cache. - prefix_indices, prefix_len = self._match_prefix_and_lock(decode_req.req) - # Align prefix_len down to page boundary so both prefill and - # decode agree on the page-aligned split point for KV transfer. page_size = self.token_to_kv_pool_allocator.page_size - if page_size > 1 and prefix_len % page_size != 0: - prefix_len = page_align_floor(prefix_len, page_size) - prefix_indices = prefix_indices[:prefix_len] - - fill_len = origin_input_len + max(len(decode_req.req.output_ids) - 1, 0) - required_alloc_tokens = self._required_alloc_tokens( - fill_len=fill_len, prefix_len=prefix_len - ) - # Matching may lock previously-evictable radix pages, so refresh - # the admission budget against the post-lock pool state before we - # decide whether this request still fits. - full_allocatable_tokens = self._allocatable_token_budgets( - retractable_tokens=retractable_tokens, - count_retracted=True, - extra_reserved_reqs=len(preallocated_reqs), + fill_len = origin_input_len + max( + len(decode_req.req.output_ids) - 1, 0 ) + + if self.enable_hicache: + # Phase 1: Match prefix (read-only, no GPU allocation) + match_result = self._match_prefix(decode_req.req) + + # Pre-check: skip load_back if request can't fit with L1-only prefix + skip_load_back = False + if match_result.host_hit_length > 0: + l1_prefix_len = len(match_result.device_indices) + if page_size > 1 and l1_prefix_len % page_size != 0: + l1_prefix_len = page_align_floor(l1_prefix_len, page_size) + conservative_alloc = self._required_alloc_tokens( + fill_len=fill_len, prefix_len=l1_prefix_len + ) + conservative_required = ( + conservative_alloc + self.num_reserved_decode_tokens + ) + conservative_projected = ( + origin_input_len + - l1_prefix_len + + min( + decode_req.req.sampling_params.max_new_tokens, + CLIP_MAX_NEW_TOKEN, + ) + - retractable_tokens + ) + if ( + max(conservative_required, conservative_projected) + > full_allocatable_tokens + ): + skip_load_back = True + + # Phase 2: Load back (if not skipped) + lock + prefix_indices, prefix_len, load_back_tokens, lock_delta = ( + self._load_back_and_lock( + decode_req.req, + match_result, + extra_load_back_budget_consumed=cumulative_load_back_tokens, + skip_load_back=skip_load_back, + ) + ) + full_allocatable_tokens += lock_delta + + # Align prefix_len down to page boundary + if page_size > 1 and prefix_len % page_size != 0: + prefix_len = page_align_floor(prefix_len, page_size) + prefix_indices = prefix_indices[:prefix_len] + + # Two-phase prefetch: trigger L3->L2 and defer prealloc if started + if decode_req.prefetch_triggered_time == 0.0: + self._trigger_prefetch_if_needed( + decode_req.req, decode_req.req.last_host_node, prefix_len + ) + if decode_req.req.rid in self.tree_cache.ongoing_prefetch: + self._unlock_prefix(decode_req.req, prefix_len) + full_allocatable_tokens -= lock_delta + decode_req.waiting_for_prefetch = True + decode_req.prefetch_triggered_time = time.monotonic() + continue + else: + decode_req.prefetch_triggered_time = time.monotonic() + + required_alloc_tokens = self._required_alloc_tokens( + fill_len=fill_len, prefix_len=prefix_len + ) + else: + # Non-HiCache radix cache path: use simple match_prefix_and_lock + prefix_indices, prefix_len = self._match_prefix_and_lock( + decode_req.req + ) + lock_delta = 0 + load_back_tokens = 0 + if page_size > 1 and prefix_len % page_size != 0: + prefix_len = page_align_floor(prefix_len, page_size) + prefix_indices = prefix_indices[:prefix_len] + required_alloc_tokens = self._required_alloc_tokens( + fill_len=fill_len, prefix_len=prefix_len + ) + full_allocatable_tokens = self._allocatable_token_budgets( + retractable_tokens=retractable_tokens, + count_retracted=True, + extra_reserved_reqs=len(preallocated_reqs), + ) else: prefix_indices = None prefix_len = 0 + lock_delta = 0 + load_back_tokens = 0 required_alloc_tokens = origin_input_len required_tokens_for_request = ( required_alloc_tokens + self.num_reserved_decode_tokens ) - if ( - max( - required_tokens_for_request, - origin_input_len - - prefix_len - + min( - decode_req.req.sampling_params.max_new_tokens, - CLIP_MAX_NEW_TOKEN, - ) - - retractable_tokens, + projected_tokens = ( + origin_input_len + - prefix_len + + min( + decode_req.req.sampling_params.max_new_tokens, + CLIP_MAX_NEW_TOKEN, ) + - retractable_tokens + ) + if ( + max(required_tokens_for_request, projected_tokens) > full_allocatable_tokens ): - if prefix_len > 0: - self.tree_cache.dec_lock_ref(decode_req.req.last_node) + # Abort if permanently stuck + if ( + len(self.scheduler.running_batch.reqs) == 0 + and len(self.transfer_queue.queue) == 0 + and projected_tokens > full_allocatable_tokens + ): + self._unlock_prefix(decode_req.req, prefix_len) + full_allocatable_tokens -= lock_delta + decode_req.req.finished_reason = FINISH_ABORT( + f"Insufficient memory: projected need " + f"~{projected_tokens} tokens but only " + f"{full_allocatable_tokens} allocatable." + ) + _cleanup_hicache_aborted_request( + self.tree_cache, self.enable_hicache, decode_req.req + ) + self.scheduler.output_streamer.stream_output( + [decode_req.req], decode_req.req.return_logprob + ) + failed_reqs.append(decode_req) + indices_to_remove.add(i) + continue + + if self.enable_hicache: + self._unlock_prefix(decode_req.req, prefix_len) + full_allocatable_tokens -= lock_delta + else: + if prefix_len > 0: + self.tree_cache.dec_lock_ref(decode_req.req.last_node) break if required_tokens_for_request > full_allocatable_tokens: - if prefix_len > 0: - self.tree_cache.dec_lock_ref(decode_req.req.last_node) + if self.enable_hicache: + self._unlock_prefix(decode_req.req, prefix_len) + full_allocatable_tokens -= lock_delta + else: + if prefix_len > 0: + self.tree_cache.dec_lock_ref(decode_req.req.last_node) break if uses_swa_tail_prealloc: @@ -889,22 +1164,53 @@ def pop_preallocated( ) > swa_allocatable_tokens ): - if prefix_len > 0: - self.tree_cache.dec_lock_ref(decode_req.req.last_node) + if self.enable_hicache: + self._unlock_prefix(decode_req.req, prefix_len) + full_allocatable_tokens -= lock_delta + else: + if prefix_len > 0: + self.tree_cache.dec_lock_ref(decode_req.req.last_node) break - dst_kv_indices = self._pre_alloc(decode_req.req, prefix_indices, prefix_len) - hisparse_req_budget -= 1 - # Recompute from actual pool state for the next queue entry. - # This accounts for page rounding and newly locked evictable cache. - full_allocatable_tokens = self._allocatable_token_budgets( - retractable_tokens=retractable_tokens, - count_retracted=True, - extra_reserved_reqs=len(preallocated_reqs) + 1, + full_allocatable_tokens -= required_tokens_for_request + if load_back_tokens > 0: + cumulative_load_back_tokens += load_back_tokens + planned_preallocs.append( + _PlannedPrealloc( + decode_req=decode_req, + prefix_indices=prefix_indices, + prefix_len=prefix_len, + required_alloc_tokens=required_alloc_tokens, + origin_input_len=origin_input_len, + ) ) + indices_to_remove.add(i) + + # --- Batch eviction then allocate --- + self._batch_evict_for_prealloc(planned_preallocs) + + for planned in planned_preallocs: + decode_req = planned.decode_req + prefix_indices = planned.prefix_indices + prefix_len = planned.prefix_len + origin_input_len = planned.origin_input_len + + dst_kv_indices = self._pre_alloc( + decode_req.req, + prefix_indices=prefix_indices, + prefix_len=prefix_len, + allow_evict=not self.enable_hicache, + ) + hisparse_req_budget -= 1 + + if not self.enable_hicache: + full_allocatable_tokens = self._allocatable_token_budgets( + retractable_tokens=retractable_tokens, + count_retracted=True, + extra_reserved_reqs=len(preallocated_reqs) + 1, + ) if uses_swa_tail_prealloc: - # SWA budget uses simple decrement (no radix cache eviction in - # the SWA pool, so page-rounding drift is negligible). + _, swa_required = self._prealloc_required_tokens(decode_req.req) swa_allocatable_tokens -= swa_required decode_req.req.cache_protected_len = prefix_len @@ -1192,11 +1498,49 @@ def _required_alloc_tokens(self, *, fill_len: int, prefix_len: int) -> int: ) return num_new_pages * page_size + def _evict_for_prealloc( + self, + required_alloc_tokens: int, + *, + req: Optional[Req] = None, + fill_len: Optional[int] = None, + prefix_len: Optional[int] = None, + delta_len: Optional[int] = None, + ) -> None: + if not self.scheduler.server_args.disaggregation_decode_enable_radix_cache: + return + + available_size = self.token_to_kv_pool_allocator.available_size() + if available_size >= required_alloc_tokens: + return + + num_to_evict = required_alloc_tokens - available_size + result = self.tree_cache.evict(EvictParams(num_tokens=num_to_evict)) + available_after = self.token_to_kv_pool_allocator.available_size() + if available_after >= required_alloc_tokens: + return + + if req is None: + return + + def _batch_evict_for_prealloc( + self, planned_preallocs: List[_PlannedPrealloc] + ) -> None: + if not planned_preallocs: + return + + total_required_alloc_tokens = sum( + planned.required_alloc_tokens for planned in planned_preallocs + ) + self._evict_for_prealloc(total_required_alloc_tokens) + def _pre_alloc( self, req: Req, prefix_indices: Optional[torch.Tensor] = None, prefix_len: Optional[int] = None, + *, + allow_evict: bool = True, ) -> torch.Tensor: """Pre-allocate the memory for req_to_token and token_kv_pool""" if prefix_len is None: @@ -1227,7 +1571,8 @@ def _pre_alloc( # Evict cached entries if the pool doesn't have enough free pages. if ( - self.scheduler.server_args.disaggregation_decode_enable_radix_cache + allow_evict + and self.scheduler.server_args.disaggregation_decode_enable_radix_cache and self.token_to_kv_pool_allocator.available_size() < required_alloc_tokens ): num_to_evict = ( diff --git a/python/sglang/srt/managers/data_parallel_controller.py b/python/sglang/srt/managers/data_parallel_controller.py index bf158695f900..8803511743cd 100644 --- a/python/sglang/srt/managers/data_parallel_controller.py +++ b/python/sglang/srt/managers/data_parallel_controller.py @@ -14,13 +14,14 @@ """A controller that dispatches requests to multiple data parallel workers.""" import faulthandler +import hashlib import logging import multiprocessing as mp import signal import threading import time from enum import Enum, auto -from typing import Callable, List, Optional +from typing import Callable, Dict, List, Optional import psutil import setproctitle @@ -69,6 +70,41 @@ SCHEDULER_PIDS_ARG = "scheduler_pids" +def _fast_chain_hash(token_ids: List[int], start: int, end: int, prior: bytes) -> bytes: + """Deterministic chained hash: SHA256 on token repr bytes. + + Unlike Python builtin hash(), SHA256 is consistent across processes. + Handles both int and tuple token IDs (e.g. EAGLE bigram mode). + """ + h = hashlib.sha256() + if prior: + h.update(prior) + h.update(repr(token_ids[start:end]).encode()) + return h.digest() + + +def estimate_prefix_match( + token_ids: List[int], + digest_entries: Dict[bytes, int], + chunk_size: int, +) -> int: + """Estimate prefix match length against a CacheDigest's prefix_entries. + + Uses the same chained-hash scheme as RadixCache.build_cache_digest() so + the hashes are comparable. Walks chunk-aligned boundaries until the + first miss. + """ + matched_len = 0 + chain_hash = b"" + for end in range(chunk_size, len(token_ids) + 1, chunk_size): + chain_hash = _fast_chain_hash(token_ids, end - chunk_size, end, chain_hash) + if chain_hash in digest_entries: + matched_len = end + else: + break + return matched_len + + class LoadBalanceMethod(Enum): """Load balance method.""" @@ -76,6 +112,7 @@ class LoadBalanceMethod(Enum): FOLLOW_BOOTSTRAP_ROOM = auto() TOTAL_REQUESTS = auto() TOTAL_TOKENS = auto() + CACHE_AWARE = auto() @classmethod def from_str(cls, method: str): @@ -91,6 +128,8 @@ def __init__(self, dp_size: int): self.dp_size = dp_size self.total_requests = [0] * dp_size self.total_tokens = [0] * dp_size + self.max_total_tokens = [0] * dp_size + self.cache_digests: List[Optional[object]] = [None] * dp_size def update_budget(self, load_update: WatchLoadUpdateReq): """Update the budget.""" @@ -99,6 +138,9 @@ def update_budget(self, load_update: WatchLoadUpdateReq): load.num_running_reqs + load.num_waiting_reqs ) self.total_tokens[load.dp_rank] = load.num_total_tokens + self.max_total_tokens[load.dp_rank] = load.max_total_num_tokens + if hasattr(load, "cache_digest") and load.cache_digest is not None: + self.cache_digests[load.dp_rank] = load.cache_digest def dispatch(self, method: LoadBalanceMethod, estimated_tokens: int = 0): if method == LoadBalanceMethod.TOTAL_REQUESTS: @@ -149,12 +191,17 @@ def __init__( LoadBalanceMethod.FOLLOW_BOOTSTRAP_ROOM: self.follow_bootstrap_room_scheduler, LoadBalanceMethod.TOTAL_REQUESTS: self.total_requests_scheduler, LoadBalanceMethod.TOTAL_TOKENS: self.total_tokens_scheduler, + LoadBalanceMethod.CACHE_AWARE: self.cache_aware_scheduler, } self.dispatching = dispatch_lookup[self.load_balance_method] # Load balance budget self.dp_budget = DPBudget(server_args.dp_size) + # Cache-aware routing params + self.dp_routing_digest_chunk_size = server_args.dp_routing_digest_chunk_size + self.dp_routing_max_extra_reqs = server_args.dp_routing_max_extra_reqs + # To protect changing env vars to set CUDA_VISIBLE_DEVICES. self.env_lock = threading.Lock() @@ -200,6 +247,16 @@ def send_control_message(self, obj): def handle_load_update_req(self, obj): self.dp_budget.update_budget(obj) + if self.load_balance_method == LoadBalanceMethod.CACHE_AWARE: + for load in obj.loads: + if hasattr(load, "cache_digest") and load.cache_digest is not None: + d = load.cache_digest + prev = getattr(self, "_prev_digest_entries", {}) + prev_count = prev.get(d.dp_rank, -1) + cur_count = len(d.prefix_entries) + if cur_count != prev_count: + prev[d.dp_rank] = cur_count + self._prev_digest_entries = prev def update_active_ranks(self, ranks: ActiveRanksOutput): self.status = ranks.status @@ -607,6 +664,104 @@ def total_tokens_scheduler(self, req: Req): ) self.workers[target_worker].send_pyobj(req) + def _rank_available_tokens(self, rank: int) -> float: + max_tok = self.dp_budget.max_total_tokens[rank] + if max_tok <= 0: + return float("inf") + used = self.dp_budget.total_tokens[rank] + digest = self.dp_budget.cache_digests[rank] + evictable = digest.evictable_tokens if digest is not None else 0 + return max_tok - used + evictable + + def cache_aware_scheduler(self, req: Req): + """Dispatch considering both prefix cache affinity and request balance. + + Logic: + 1. Estimate cache match length on each active DP rank. + 2. Pick the ranks with the longest match. + 3. Among those, pick the one with fewest requests. + 4. But if that rank already has more requests than the + least-loaded rank by >= max_extra_reqs, ignore cache + and pick the least-loaded rank instead. + 5. If the chosen rank doesn't have enough capacity for the + request, pick the least-loaded rank that does. + """ + if self.maybe_external_dp_rank_routing(req): + return + + rid = getattr(req, "rid", "") + if isinstance(rid, str) and rid.startswith("HEALTH_CHECK_"): + self.round_robin_scheduler(req) + return + + dp_size = len(self.workers) + chunk_size = self.dp_routing_digest_chunk_size + max_extra = self.dp_routing_max_extra_reqs + + token_ids = getattr(req, "input_ids", None) + if token_ids is None: + token_ids = getattr(req, "origin_input_ids", None) + + active_ranks = [i for i in range(dp_size) if self.status[i]] + if not active_ranks: + active_ranks = list(range(dp_size)) + + has_any_digest = any( + self.dp_budget.cache_digests[r] is not None for r in active_ranks + ) + if not has_any_digest or not token_ids or len(token_ids) < chunk_size: + estimated_tokens = len(token_ids) if token_ids else 0 + target = self.dp_budget.dispatch( + LoadBalanceMethod.TOTAL_TOKENS, estimated_tokens=estimated_tokens + ) + if target is None: + target = active_ranks[self.round_robin_counter % len(active_ranks)] + self.round_robin_counter += 1 + self.workers[target].send_pyobj(req) + return + + match_info: Dict[int, int] = {} + for rank in active_ranks: + digest = self.dp_budget.cache_digests[rank] + if digest is not None and digest.prefix_entries: + match_info[rank] = estimate_prefix_match( + token_ids, digest.prefix_entries, chunk_size + ) + else: + match_info[rank] = 0 + + best_match = max(match_info.values()) + if best_match > 0: + candidates = [r for r in active_ranks if match_info[r] == best_match] + else: + candidates = active_ranks + + best_rank = min(candidates, key=lambda r: self.dp_budget.total_requests[r]) + + min_reqs = min(self.dp_budget.total_requests[r] for r in active_ranks) + if self.dp_budget.total_requests[best_rank] - min_reqs >= max_extra: + best_rank = min( + active_ranks, key=lambda r: self.dp_budget.total_requests[r] + ) + + input_len = len(token_ids) + needed = input_len - match_info.get(best_rank, 0) + available = self._rank_available_tokens(best_rank) + if needed > available: + viable = [ + r + for r in active_ranks + if r != best_rank + and self._rank_available_tokens(r) >= input_len - match_info.get(r, 0) + ] + if viable: + best_rank = min( + viable, key=lambda r: self.dp_budget.total_requests[r] + ) + + self.dp_budget.total_requests[best_rank] += 1 + self.workers[best_rank].send_pyobj(req) + def event_loop(self): while True: while True: diff --git a/python/sglang/srt/managers/io_struct.py b/python/sglang/srt/managers/io_struct.py index 293335f646d1..0b9dfa140c27 100644 --- a/python/sglang/srt/managers/io_struct.py +++ b/python/sglang/srt/managers/io_struct.py @@ -2038,6 +2038,16 @@ def __post_init__(self): ) +@dataclass +class CacheDigest: + dp_rank: int + prefix_entries: Dict[bytes, int] + total_cached_tokens: int + evictable_tokens: int + protected_tokens: int + timestamp: float + + @dataclass class GetLoadsReqOutput(BaseReq): """Per-DP-rank load metrics for /v1/loads endpoint.""" @@ -2083,6 +2093,7 @@ class GetLoadsReqOutput(BaseReq): lora: Optional[LoRAMetrics] = None disaggregation: Optional[DisaggregationMetrics] = None queues: Optional[QueueMetrics] = None + cache_digest: Optional[CacheDigest] = None @dataclass diff --git a/python/sglang/srt/managers/scheduler.py b/python/sglang/srt/managers/scheduler.py index 8bccdd219fd3..9113b8caefc5 100644 --- a/python/sglang/srt/managers/scheduler.py +++ b/python/sglang/srt/managers/scheduler.py @@ -449,6 +449,24 @@ def __init__( self.disable_radix_cache = result.disable_radix_cache self.tree_cache = result.tree_cache + # Decode radix cache is unsupported with hybrid SWA/SSM models — + # these use specialized memory pools incompatible with the + # prefix-match-and-lock allocation path. + if ( + server_args.disaggregation_decode_enable_radix_cache + and server_args.disaggregation_mode == "decode" + ): + if self.is_hybrid_swa: + raise ValueError( + "--disaggregation-decode-enable-radix-cache is incompatible " + "with sliding window attention (SWA) models" + ) + if self.is_hybrid_ssm: + raise ValueError( + "--disaggregation-decode-enable-radix-cache is incompatible " + "with Mamba/SSM models" + ) + if self.enable_hisparse: # Coordinator was created inside ModelRunner.initialize() before CUDA graph capture self.hisparse_coordinator = self.tp_worker.model_runner.hisparse_coordinator @@ -660,6 +678,7 @@ def __init__( get_disagg_decode_transfer_queue=lambda: self.disagg_decode_transfer_queue, get_spec_total_num_accept_tokens=lambda: self.metrics_reporter.spec_total_num_accept_tokens, get_spec_total_num_forward_ct=lambda: self.metrics_reporter.spec_total_num_forward_ct, + get_tree_cache=lambda: self.tree_cache, ) self.output_streamer = SchedulerOutputStreamer( diff --git a/python/sglang/srt/managers/scheduler_components/load_inquirer.py b/python/sglang/srt/managers/scheduler_components/load_inquirer.py index 32acaa44ee7b..3412d4fd5917 100644 --- a/python/sglang/srt/managers/scheduler_components/load_inquirer.py +++ b/python/sglang/srt/managers/scheduler_components/load_inquirer.py @@ -7,6 +7,7 @@ from sglang.srt.disaggregation.utils import DisaggregationMode from sglang.srt.managers.io_struct import ( + CacheDigest, DisaggregationMetrics, GetLoadsReqInput, GetLoadsReqOutput, @@ -51,6 +52,7 @@ class SchedulerLoadInquirer: get_disagg_decode_transfer_queue: Callable get_spec_total_num_accept_tokens: Callable get_spec_total_num_forward_ct: Callable + get_tree_cache: Callable def _get_num_pending_tokens(self, chunk_deduct: int = 0) -> int: """Get the total number of tokens pending prefill. @@ -188,6 +190,29 @@ def get_loads(self, req: GetLoadsReqInput = None) -> GetLoadsReqOutput: retracted=self.get_stats().num_retracted_reqs, ) + cache_digest = None + if ( + self.disaggregation_mode == DisaggregationMode.DECODE + and self.server_args.disaggregation_decode_enable_radix_cache + ): + tree_cache = self.get_tree_cache() + if hasattr(tree_cache, "build_cache_digest"): + dirty = getattr(tree_cache, "_digest_dirty", True) + if dirty or not hasattr(tree_cache, "_cached_cache_digest"): + chunk_size = self.server_args.dp_routing_digest_chunk_size + digest_data = tree_cache.build_cache_digest( + chunk_size=chunk_size, + ) + tree_cache._cached_cache_digest = CacheDigest( + dp_rank=self.ps.dp_rank, + prefix_entries=digest_data["prefix_entries"], + total_cached_tokens=digest_data["total_cached_tokens"], + evictable_tokens=digest_data["evictable_tokens"], + protected_tokens=digest_data["protected_tokens"], + timestamp=time.time(), + ) + cache_digest = tree_cache._cached_cache_digest + return GetLoadsReqOutput( dp_rank=self.ps.dp_rank, timestamp=time.time(), @@ -206,4 +231,5 @@ def get_loads(self, req: GetLoadsReqInput = None) -> GetLoadsReqOutput: lora=lora, disaggregation=disaggregation, queues=queues, + cache_digest=cache_digest, ) diff --git a/python/sglang/srt/mem_cache/hiradix_cache.py b/python/sglang/srt/mem_cache/hiradix_cache.py index 3416d2a86e66..8f9dfbc7c5f3 100644 --- a/python/sglang/srt/mem_cache/hiradix_cache.py +++ b/python/sglang/srt/mem_cache/hiradix_cache.py @@ -806,6 +806,11 @@ def loading_check(self): def evictable_size(self): return self.evictable_size_ + def _skip_node_in_digest(self, node: TreeNode) -> bool: + # Include evicted nodes that have a host backup — they are recoverable + # via load_back() and should be visible to cache-aware DP routing. + return node.evicted and not node.backuped + def _to_radix_key(self, token_ids: List[int]) -> RadixKey: """Convert raw token_ids to a RadixKey; must be list (not tuple) for paged match.""" return RadixKey(token_ids=list(token_ids)) @@ -909,6 +914,8 @@ def evict(self, params: EvictParams) -> EvictResult: self._evict_backuped(node) self.update_eviction_metrics(num_evicted, start_time) + if num_evicted > 0: + self._digest_dirty = True return EvictResult(num_tokens_evicted=num_evicted) def _evict_backuped(self, node: TreeNode): @@ -1034,6 +1041,7 @@ def load_back( self._record_store_event(node, medium=StorageMedium.GPU) self.evictable_size_ += len(device_indices) self.inc_lock_ref(last_hit_node) + self._digest_dirty = True if self.metrics_collector is not None: self.metrics_collector.observe_load_back_duration( @@ -1052,9 +1060,6 @@ def init_load_back( if last_node.evicted: loading_values = self.load_back(last_node, mem_quota) if loading_values is not None: - logger.debug( - f"loading back {len(loading_values)} tokens for node {last_node.id}" - ) return loading_values, last_node while last_node.evicted: @@ -1172,7 +1177,6 @@ def check_prefetch_progress(self, req_id: str) -> bool: completed_tokens, hash_value = self.cache_controller.terminate_prefetch( operation ) - logger.debug(f"Prefetch {req_id} completed with {completed_tokens} tokens") min_completed_tokens = completed_tokens # Synchronize workers before mutating host cache tree state. @@ -1374,6 +1378,11 @@ def _match_prefix_helper(self, node: TreeNode, key: RadixKey): else: if not child.evicted: value.append(child.value) + else: + # Stop at evicted boundary — continuing would create + # a gap in device_indices if a descendant was re-filled. + node = child + break node = child key = key[prefix_len:] @@ -1439,13 +1448,14 @@ def insert(self, params: InsertParams) -> InsertResult: if prefix_len == len(node.key): if node.evicted: - # change the reference if the node is evicted - # this often happens in the case of KV cache recomputation node.value = value[:prefix_len].clone() + if node.backuped: + self.cache_controller.mem_pool_host.free(node.host_value) + node.host_value = None + node.backuped = False self.evictable_size_ += len(node.value) self._update_leaf_status(node) self._update_host_leaf_status(node) - # update parent status as a new leaf is added into device self._update_leaf_status(node.parent) else: self._inc_hit_count(node, chunked) @@ -1457,10 +1467,13 @@ def insert(self, params: InsertParams) -> InsertResult: new_node.priority = max(new_node.priority, priority) if new_node.evicted: new_node.value = value[:prefix_len].clone() + if new_node.backuped: + self.cache_controller.mem_pool_host.free(new_node.host_value) + new_node.host_value = None + new_node.backuped = False self.evictable_size_ += len(new_node.value) self._update_leaf_status(new_node) self._update_host_leaf_status(new_node) - # update parent status as a new leaf is added into device self._update_leaf_status(new_node.parent) else: self._inc_hit_count(new_node, chunked) @@ -1492,6 +1505,7 @@ def insert(self, params: InsertParams) -> InsertResult: if self.cache_controller.write_policy != "write_back": self._inc_hit_count(new_node, chunked) + self._digest_dirty = True return InsertResult(prefix_len=total_prefix_length) def release_aborted_request(self, rid: str): diff --git a/python/sglang/srt/mem_cache/radix_cache.py b/python/sglang/srt/mem_cache/radix_cache.py index 5f8a256f6674..a75959f09a51 100644 --- a/python/sglang/srt/mem_cache/radix_cache.py +++ b/python/sglang/srt/mem_cache/radix_cache.py @@ -344,6 +344,7 @@ def reset(self): self.root_node.hash_value = [] self.evictable_size_ = 0 self.protected_size_ = 0 + self._digest_dirty = True self.evictable_leaves.clear() self._empty_match_result = MatchResult( device_indices=torch.empty( @@ -435,6 +436,7 @@ def insert(self, params: InsertParams) -> InsertResult: value = torch.tensor(key.token_ids[: len(key)], dtype=torch.int64) prefix_len = self._insert_helper(self.root_node, key, value, priority, chunked) + self._digest_dirty = True return InsertResult(prefix_len=prefix_len) def cache_finished_req(self, req: Req, is_insert: bool = True): @@ -584,6 +586,8 @@ def evict(self, params: EvictParams) -> EvictResult: self._record_remove_event(x) self.update_eviction_metrics(num_evicted, start_time) + if num_evicted > 0: + self._digest_dirty = True return EvictResult(num_tokens_evicted=num_evicted) def inc_lock_ref(self, node: TreeNode) -> IncLockRefResult: @@ -629,6 +633,86 @@ def protected_size(self): # protected size refers to the size of the cache that is locked return self.protected_size_ + def _skip_node_in_digest(self, node: TreeNode) -> bool: + """Whether to skip *node* when building a cache digest. + + RadixCache skips evicted nodes (GPU data gone, unrecoverable). + HiRadixCache overrides this to keep evicted nodes that still have + a host backup, since they can be recovered via load_back(). + """ + return node.evicted + + def build_cache_digest( + self, + chunk_size: int = 256, + max_entries: int = 2048, + max_prefix_tokens: int = 8192, + ) -> dict: + """Build a compact digest of cached prefixes for cache-aware DP routing. + + Traverses the radix tree and produces chunk-aligned prefix hashes. + Each entry maps hash(token_ids[:chunk_boundary]) -> cached_length, + allowing the DP controller to estimate prefix match length for incoming + requests without accessing the actual tree. + + Uses a deterministic chained hash: SHA256 on repr-encoded token + bytes, matching the estimation function in the DP controller. + + Returns a dict ready to populate a CacheDigest dataclass. + """ + prefix_entries: dict = {} + + stack: list = [(self.root_node, [], b"", 0)] + while stack: + node, parent_tokens, parent_chain_hash, parent_boundary = stack.pop() + + for child in node.children.values(): + if self._skip_node_in_digest(child): + continue + + path_tokens = parent_tokens + child.key.token_ids + if len(path_tokens) > max_prefix_tokens: + path_tokens = path_tokens[:max_prefix_tokens] + + chain_hash = parent_chain_hash + first_boundary = parent_boundary + chunk_size + + last_boundary = parent_boundary + for boundary in range(first_boundary, len(path_tokens) + 1, chunk_size): + h = hashlib.sha256() + if chain_hash: + h.update(chain_hash) + chunk = path_tokens[boundary - chunk_size : boundary] + h.update(repr(chunk).encode()) + chain_hash = h.digest() + prefix_entries[chain_hash] = max( + prefix_entries.get(chain_hash, 0), boundary + ) + last_boundary = boundary + + if len(prefix_entries) >= max_entries: + break + + if len(prefix_entries) >= max_entries: + break + + if len(path_tokens) < max_prefix_tokens and child.children: + stack.append( + (child, path_tokens, chain_hash, last_boundary) + ) + + if len(prefix_entries) >= max_entries: + break + + total = self._total_size_helper() + self._digest_dirty = False + return { + "prefix_entries": prefix_entries, + "total_cached_tokens": total, + "evictable_tokens": self.evictable_size_, + "protected_tokens": self.protected_size_, + } + def all_values_flatten(self): values = [] diff --git a/python/sglang/srt/server_args.py b/python/sglang/srt/server_args.py index 9c5e2822f55e..683eb2d9cbb6 100644 --- a/python/sglang/srt/server_args.py +++ b/python/sglang/srt/server_args.py @@ -770,11 +770,19 @@ class ServerArgs: disaggregation_bootstrap_port: int = 8998 disaggregation_ib_device: Optional[str] = None disaggregation_decode_enable_radix_cache: bool = False + disaggregation_decode_enable_hicache: bool = False + disaggregation_decode_hicache_ratio: float = 1.0 + disaggregation_decode_hicache_size: int = 0 + disaggregation_decode_hicache_write_policy: str = "write_through" disaggregation_decode_enable_offload_kvcache: bool = False num_reserved_decode_tokens: int = 512 # used for decode kv cache offload in PD # FIXME: hack to reduce ITL when decode bs is small disaggregation_decode_polling_interval: int = 1 + # Cache-aware DP routing (decode multi-DP) + dp_routing_digest_chunk_size: int = 256 + dp_routing_max_extra_reqs: int = 1 + # Encode prefill disaggregation encoder_only: bool = False language_only: bool = False @@ -993,12 +1001,18 @@ def _handle_load_balance_method(self): # Default behavior: # - non-PD: round_robin # - PD prefill: follow_bootstrap_room - # - PD decode: round_robin - self.load_balance_method = ( - "follow_bootstrap_room" - if self.disaggregation_mode == "prefill" - else "round_robin" - ) + # - PD decode + radix cache + dp > 1: cache_aware + # - PD decode (other): round_robin + if self.disaggregation_mode == "prefill": + self.load_balance_method = "follow_bootstrap_room" + elif ( + self.disaggregation_mode == "decode" + and self.disaggregation_decode_enable_radix_cache + and self.dp_size > 1 + ): + self.load_balance_method = "cache_aware" + else: + self.load_balance_method = "round_robin" return def _handle_ssl_validation(self): @@ -3681,6 +3695,21 @@ def _handle_pd_disaggregation(self): ) self.disable_radix_cache = False logger.warning("EXPERIMENTAL: Radix cache is enabled for decode server") + + if self.disaggregation_decode_enable_hicache: + self.enable_hierarchical_cache = True + if self.disaggregation_decode_hicache_size > 0: + self.hicache_size = self.disaggregation_decode_hicache_size + else: + self.hicache_ratio = self.disaggregation_decode_hicache_ratio + self.hicache_write_policy = ( + self.disaggregation_decode_hicache_write_policy + ) + logger.warning( + "EXPERIMENTAL: HiRadixCache is enabled for decode server " + f"(ratio={self.hicache_ratio}, " + f"write_policy={self.hicache_write_policy})" + ) else: self.disable_radix_cache = True logger.warning("KV cache is forced as chunk cache for decode server") @@ -5160,6 +5189,7 @@ def add_cli_args(parser: argparse.ArgumentParser): "follow_bootstrap_room", "total_requests", "total_tokens", + "cache_aware", ], ) parser.add_argument( @@ -6522,6 +6552,30 @@ def add_cli_args(parser: argparse.ArgumentParser): action="store_true", help="Enable radix cache on decode server (PD mode). Caches KV prefixes to avoid redundant transfers. Requires --disaggregation-transfer-backend nixl or mooncake and is incompatible with --enable-hisparse.", ) + parser.add_argument( + "--disaggregation-decode-enable-hicache", + action="store_true", + help="Enable hierarchical cache (HiRadixCache) on decode server (PD mode). Requires --disaggregation-decode-enable-radix-cache. Adds host (L2) and optional storage (L3) cache layers.", + ) + parser.add_argument( + "--disaggregation-decode-hicache-ratio", + type=float, + default=ServerArgs.disaggregation_decode_hicache_ratio, + help="The ratio of host KV cache memory pool to device pool for decode server HiRadixCache.", + ) + parser.add_argument( + "--disaggregation-decode-hicache-size", + type=int, + default=ServerArgs.disaggregation_decode_hicache_size, + help="The size of host KV cache memory pool in GB for decode server HiRadixCache. Overrides --disaggregation-decode-hicache-ratio if set.", + ) + parser.add_argument( + "--disaggregation-decode-hicache-write-policy", + type=str, + choices=["write_back", "write_through", "write_through_selective"], + default=ServerArgs.disaggregation_decode_hicache_write_policy, + help="The write policy for decode server HiRadixCache.", + ) parser.add_argument( "--disaggregation-decode-enable-offload-kvcache", action="store_true", @@ -6540,6 +6594,20 @@ def add_cli_args(parser: argparse.ArgumentParser): help="The interval to poll requests in decode server. Can be set to >1 to reduce the overhead of this.", ) + # Cache-aware DP routing + parser.add_argument( + "--dp-routing-digest-chunk-size", + type=int, + default=ServerArgs.dp_routing_digest_chunk_size, + help="Chunk size (in tokens) for CacheDigest prefix hashing. Default 256.", + ) + parser.add_argument( + "--dp-routing-max-extra-reqs", + type=int, + default=ServerArgs.dp_routing_max_extra_reqs, + help="Max extra requests a cache-preferred rank can have over the least-loaded rank before falling back to load balance. Default 1.", + ) + # Encode prefill disaggregation parser.add_argument( "--encoder-only",