Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
5 changes: 0 additions & 5 deletions python/sglang/srt/managers/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3065,11 +3065,6 @@ def update_running_batch(self, batch: ScheduleBatch) -> Optional[ScheduleBatch]:
batch.batch_is_full = False
return batch

# Eagerly release lock_ref on completed write-through nodes so they
# become evictable, improving batch scheduling headroom.
if self.enable_hierarchical_cache:
self.tree_cache.flush_write_through_acks()

# Check if decode out of memory
if (kv_full_retract_flag := not batch.check_decode_mem()) or (
TEST_RETRACT and self.forward_ct % TEST_RETRACT_INTERVAL == 0
Expand Down
8 changes: 0 additions & 8 deletions python/sglang/srt/mem_cache/base_prefix_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,14 +308,6 @@ def ready_to_load_host_cache(self) -> Any:
"""
raise NotImplementedError()

def flush_write_through_acks(self) -> None:
"""Release lock_ref on radix-tree nodes whose write-through has completed.

Lightweight operation that only processes finished write acks.
No-op for caches without hierarchical write-through support.
"""
pass

def check_hicache_events(self) -> Any:
"""
Check HiCache related activities to update radix tree and synchronize across TP workers if needed
Expand Down
3 changes: 0 additions & 3 deletions python/sglang/srt/mem_cache/hi_mamba_radix_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,9 +455,6 @@ def loading_check(self):
def ready_to_load_host_cache(self) -> int:
return self.cache_controller.start_loading()

def flush_write_through_acks(self) -> None:
self.writing_check()

def check_hicache_events(self):
self.writing_check()
self.loading_check()
Expand Down
118 changes: 86 additions & 32 deletions python/sglang/srt/mem_cache/hiradix_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,6 @@ def __init__(self, params: CacheInitParams, server_args: ServerArgs):
1 if server_args.hicache_write_policy == "write_through" else 2
)
self.load_back_threshold = 10

# Detach storage backend automatically on process shutdown
atexit.register(self.shutdown)

Expand Down Expand Up @@ -929,7 +928,42 @@ def _inc_hit_count(self, node: TreeNode, chunked=False):
# write to host if the node is not backuped
self.write_backup(node)

def writing_check(self, write_back=False):
@staticmethod
def _count_ready_acks(ack_queue) -> int:
ready_count = 0
for _, finish_event, _ in ack_queue:
if not finish_event.query():
break
ready_count += 1
return ready_count

def _sync_hicache_ready_counts(self) -> tuple[int, int, tuple[int, ...]]:
cache_controller = self.cache_controller
storage_queue_sizes = (
(
cache_controller.prefetch_revoke_queue.qsize(),
cache_controller.ack_backup_queue.qsize(),
cache_controller.host_mem_release_queue.qsize(),
)
if self.enable_storage
else ()
)

ready_counts = torch.tensor(
[
self._count_ready_acks(cache_controller.ack_write_queue),
self._count_ready_acks(cache_controller.ack_load_queue),
*storage_queue_sizes,
],
dtype=torch.int,
device="cpu",
)
self._all_reduce(ready_counts, torch.distributed.ReduceOp.MIN)

count_values = list(map(int, ready_counts.tolist()))
return count_values[0], count_values[1], tuple(count_values[2:])

def writing_check(self, write_back=False, finish_count: Optional[int] = None):
if write_back:
# blocking till all write back complete
while len(self.ongoing_write_through) > 0:
Expand All @@ -941,19 +975,21 @@ def writing_check(self, write_back=False):
assert len(self.ongoing_write_through) == 0
return

# Every rank must enter the all_reduce below; ongoing_write_through can
# diverge across ranks (e.g. write_backup returning 0 on a subset under
# host memory pressure), so a conditional skip desyncs the NCCL op
# sequence and deadlocks under TP > 1. (Matches UnifiedRadixCache.)
finish_count = 0
if self.pp_rank == 0:
for _, finish_event, ack_list in self.cache_controller.ack_write_queue:
if not finish_event.query():
break
finish_count += 1
finish_count_tensor = torch.tensor(finish_count, dtype=torch.int, device="cpu")
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()
if finish_count is None:
# Every rank must enter the all_reduce below; ongoing_write_through can
# diverge across ranks (e.g. write_backup returning 0 on a subset under
# host memory pressure), so a conditional skip desyncs the NCCL op
# sequence and deadlocks under TP > 1. (Matches UnifiedRadixCache.)
finish_count = 0
if self.pp_rank == 0:
finish_count = self._count_ready_acks(
self.cache_controller.ack_write_queue
)
finish_count_tensor = torch.tensor(
finish_count, dtype=torch.int, device="cpu"
)
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()

if finish_count > 0:
logger.debug(f"Process {finish_count} write back operations")
Expand All @@ -964,16 +1000,18 @@ def writing_check(self, write_back=False):
self._finish_write_through_ack(ack_id, release_lock=True)
finish_count -= 1

def loading_check(self):
finish_count = 0
if self.pp_rank == 0:
for _, finish_event, ack_list in self.cache_controller.ack_load_queue:
if not finish_event.query():
break
finish_count += 1
finish_count_tensor = torch.tensor(finish_count, dtype=torch.int, device="cpu")
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()
def loading_check(self, finish_count: Optional[int] = None):
if finish_count is None:
finish_count = 0
if self.pp_rank == 0:
finish_count = self._count_ready_acks(
self.cache_controller.ack_load_queue
)
finish_count_tensor = torch.tensor(
finish_count, dtype=torch.int, device="cpu"
)
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()

if finish_count > 0:
logger.debug(f"Process {finish_count} load operations")
Expand Down Expand Up @@ -1388,16 +1426,32 @@ def ready_to_load_host_cache(self) -> int:
"""
return self.cache_controller.start_loading()

def flush_write_through_acks(self) -> None:
self.writing_check()

def check_hicache_events(self):
# Reap the previous round's PP-sync sends before issuing new ones.
self._drain_async_work()
self.writing_check()
self.loading_check()
if self.enable_storage:
self.drain_storage_control_queues()

if self.pp_size != 1:
self.writing_check()
self.loading_check()
if self.enable_storage:
self.drain_storage_control_queues()
else:
(
write_finish_count,
load_finish_count,
storage_queue_sizes,
) = self._sync_hicache_ready_counts()
self.writing_check(finish_count=write_finish_count)
self.loading_check(finish_count=load_finish_count)

if self.enable_storage and storage_queue_sizes:
n_revoke, n_backup, n_release = storage_queue_sizes[:3]
self._drain_storage_control_queues_impl(
n_revoke=n_revoke,
n_backup=n_backup,
n_release=n_release,
log_metrics=True,
)
if self.enable_storage_metrics:
self.storage_metrics_collector.log_storage_metrics(
self.cache_controller.storage_backend.get_stats()
Expand Down
4 changes: 2 additions & 2 deletions python/sglang/srt/mem_cache/storage/flexkv/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -379,8 +379,8 @@ Supported:
here but requires `PoolTransfer` + `PoolHitPolicy` plumbing in
`FlexKVConnector`.
* Write-back acks are per-request (one `dec_lock_ref` per
`cache_finished_req`), not per-page like HiCache's
`flush_write_through_acks`.
`cache_finished_req`), not per-page like HiCache's write-through
ack queues.
* `--radix-cache-backend=flexkv` and `--enable-flexkv` are
mutually equivalent today; we don't yet emit a deprecation
warning if both are set.
Expand Down
147 changes: 114 additions & 33 deletions python/sglang/srt/mem_cache/unified_radix_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -2330,7 +2330,64 @@ def clear_storage_backend(self) -> bool:

# ---- HiCache: Async Event Management ----

def writing_check(self, write_back: bool = False) -> None:
@staticmethod
def _count_ready_acks(ack_queue) -> int:
ready_count = 0
for _, finish_event, _ in ack_queue:
if not finish_event.query():
break
ready_count += 1
return ready_count

def _sync_hicache_ready_counts(
self,
) -> tuple[int, int, tuple[int, ...], tuple[PoolName, ...]]:
cc = self.cache_controller
if cc is None:
write_acks = 0
load_acks = 0
storage_queue_sizes = ()
extra_pool_names = ()
else:
write_acks = self._count_ready_acks(cc.ack_write_queue)
load_acks = self._count_ready_acks(cc.ack_load_queue)
extra_release_queues = getattr(cc, "extra_host_mem_release_queues", {})
extra_pool_names = (
tuple(extra_release_queues) if self.enable_storage else ()
)
storage_queue_sizes = (
(
cc.prefetch_revoke_queue.qsize(),
cc.ack_backup_queue.qsize(),
cc.host_mem_release_queue.qsize(),
*(extra_release_queues[name].qsize() for name in extra_pool_names),
)
if self.enable_storage
else ()
)

ready_counts = torch.tensor(
[
write_acks,
load_acks,
*storage_queue_sizes,
],
dtype=torch.int,
device="cpu",
)
self._all_reduce(ready_counts, torch.distributed.ReduceOp.MIN)

count_values = list(map(int, ready_counts.tolist()))
return (
count_values[0],
count_values[1],
tuple(count_values[2:]),
extra_pool_names,
)

def writing_check(
self, write_back: bool = False, finish_count: Optional[int] = None
) -> None:
"""Poll write-through completions."""
cc = self.cache_controller
if cc is None:
Expand All @@ -2348,18 +2405,17 @@ def writing_check(self, write_back: bool = False) -> None:
assert len(self.ongoing_write_through) == 0
return

# Every rank must enter the all_reduce below; ongoing_write_through can
# diverge across ranks (e.g. write_backup returning 0 on a subset).
finish_count = 0
if self.pp_rank == 0:
for _, finish_event, ack_list in cc.ack_write_queue:
if not finish_event.query():
break
finish_count += 1

finish_count_tensor = torch.tensor(finish_count, dtype=torch.int, device="cpu")
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()
if finish_count is None:
# Every rank must enter the all_reduce below; ongoing_write_through can
# diverge across ranks (e.g. write_backup returning 0 on a subset).
finish_count = 0
if self.pp_rank == 0:
finish_count = self._count_ready_acks(cc.ack_write_queue)
finish_count_tensor = torch.tensor(
finish_count, dtype=torch.int, device="cpu"
)
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()

# Process completed acks
while finish_count > 0:
Expand All @@ -2369,22 +2425,23 @@ def writing_check(self, write_back: bool = False) -> None:
self._finish_write_through_ack(ack_id)
finish_count -= 1

def loading_check(self) -> None:
def loading_check(self, finish_count: Optional[int] = None) -> None:
"""Poll load-back completions."""
cc = self.cache_controller
if cc is None:
return
# Every rank must enter the all_reduce below; ongoing_load_back can
# diverge across ranks.
finish_count = 0
if self.pp_rank == 0:
for _, finish_event, ack_list in cc.ack_load_queue:
if not finish_event.query():
break
finish_count += 1
finish_count_tensor = torch.tensor(finish_count, dtype=torch.int, device="cpu")
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()

if finish_count is None:
# Every rank must enter the all_reduce below; ongoing_load_back can
# diverge across ranks.
finish_count = 0
if self.pp_rank == 0:
finish_count = self._count_ready_acks(cc.ack_load_queue)
finish_count_tensor = torch.tensor(
finish_count, dtype=torch.int, device="cpu"
)
self._all_reduce(finish_count_tensor, torch.distributed.ReduceOp.MIN)
finish_count = finish_count_tensor.item()

while finish_count > 0:
_, finish_event, ack_list = cc.ack_load_queue.pop(0)
Expand Down Expand Up @@ -2454,19 +2511,43 @@ def check_hicache_events(self) -> None:
"""Called per scheduler step to poll async HiCache events."""
# Reap the previous round's PP-sync sends before issuing new ones.
self._drain_async_work()
self.writing_check()
self.loading_check()
if self.enable_storage:
self.drain_storage_control_queues()

if self.pp_size != 1:
self.writing_check()
self.loading_check()
if self.enable_storage:
self.drain_storage_control_queues()
else:
(
write_finish_count,
load_finish_count,
storage_queue_sizes,
extra_pool_names,
) = self._sync_hicache_ready_counts()
self.writing_check(finish_count=write_finish_count)
self.loading_check(finish_count=load_finish_count)

if self.enable_storage and storage_queue_sizes:
n_revoke, n_backup, n_release = storage_queue_sizes[:3]
extra_release_counts = {
pool_name: count
for pool_name, count in zip(
extra_pool_names,
storage_queue_sizes[3:],
)
}
self._drain_storage_control_queues_impl(
n_revoke=n_revoke,
n_backup=n_backup,
n_release=n_release,
extra_release_counts=extra_release_counts,
log_metrics=True,
)
if self.enable_storage_metrics and self.storage_metrics_collector is not None:
self.storage_metrics_collector.log_storage_metrics(
self.cache_controller.storage_backend.get_stats()
)

def flush_write_through_acks(self) -> None:
"""Flush pending write-through acknowledgements."""
self.writing_check()

def ready_to_load_host_cache(self) -> int:
"""Notify the cache controller to start the KV cache loading."""
if self.cache_controller is not None:
Expand Down
3 changes: 0 additions & 3 deletions python/sglang/srt/session/streaming_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,9 +604,6 @@ def init_load_back(self, params: InitLoadBackParams):
def ready_to_load_host_cache(self):
return self.inner.ready_to_load_host_cache()

def flush_write_through_acks(self) -> None:
return self.inner.flush_write_through_acks()

def check_hicache_events(self):
return self.inner.check_hicache_events()

Expand Down
Loading