Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
439 changes: 392 additions & 47 deletions python/sglang/srt/disaggregation/decode.py

Large diffs are not rendered by default.

157 changes: 156 additions & 1 deletion python/sglang/srt/managers/data_parallel_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -69,13 +70,49 @@
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."""

ROUND_ROBIN = auto()
FOLLOW_BOOTSTRAP_ROOM = auto()
TOTAL_REQUESTS = auto()
TOTAL_TOKENS = auto()
CACHE_AWARE = auto()

@classmethod
def from_str(cls, method: str):
Expand All @@ -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."""
Expand All @@ -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:
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
11 changes: 11 additions & 0 deletions python/sglang/srt/managers/io_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions python/sglang/srt/managers/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from sglang.srt.disaggregation.utils import DisaggregationMode
from sglang.srt.managers.io_struct import (
CacheDigest,
DisaggregationMetrics,
GetLoadsReqInput,
GetLoadsReqOutput,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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(),
Expand All @@ -206,4 +231,5 @@ def get_loads(self, req: GetLoadsReqInput = None) -> GetLoadsReqOutput:
lora=lora,
disaggregation=disaggregation,
queues=queues,
cache_digest=cache_digest,
)
Loading
Loading