[Bugfix] Defer block freeing until in-flight steps finish under async scheduling + PD KV consumer (#45357)

Signed-off-by: llx-08 <2596671364@qq.com>
Signed-off-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: Jiangyun Zhu <riverclouds.zhu@qq.com>
This commit is contained in:
llx
2026-06-15 21:36:09 +00:00
committed by GitHub
co-authored by Nick Hill Jiangyun Zhu
parent 76a373eff4
commit d467a2a7f2
9 changed files with 543 additions and 20 deletions
+19
View File
@@ -291,6 +291,25 @@ class KVCacheCoordinator(ABC):
for manager in self.single_type_managers:
manager.free(request_id)
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
"""
Pop the request's bookkeeping from all single-type managers and
return its blocks without returning them to the block pool. The
caller must eventually pass the returned blocks to
`block_pool.free_blocks`, freeing them in reverse order (so that
tail blocks are evicted first).
Args:
request_id: The request ID.
Returns:
The request's blocks in allocation order.
"""
blocks: list[KVCacheBlock] = []
for manager in self.single_type_managers:
blocks.extend(manager.pop_blocks_for_free(request_id))
return blocks
def get_num_common_prefix_blocks(self, running_request_id: str) -> list[int]:
"""
Get the number of common prefix blocks for all requests with allocated
+13
View File
@@ -480,6 +480,19 @@ class KVCacheManager:
"""
self.coordinator.remove_skipped_blocks(request_id, total_computed_tokens)
def pop_blocks_for_free(self, request: Request) -> list[KVCacheBlock]:
"""Pop the request's bookkeeping and return its blocks without
returning them to the block pool. The caller must eventually free
them in reverse order (so that tail blocks are evicted first).
Args:
request: The request to pop the blocks for.
Returns:
The request's blocks in allocation order.
"""
return self.coordinator.pop_blocks_for_free(request.request_id)
def evict_blocks(self, block_ids: set[int]) -> None:
"""evict blocks from the prefix cache by their block IDs.
+67 -6
View File
@@ -37,6 +37,7 @@ from vllm.v1.core.encoder_cache_manager import (
from vllm.v1.core.kv_cache_coordinator import HybridKVCacheCoordinator
from vllm.v1.core.kv_cache_manager import KVCacheBlocks, KVCacheManager
from vllm.v1.core.kv_cache_metrics import KVCacheMetricsCollector
from vllm.v1.core.kv_cache_utils import KVCacheBlock
from vllm.v1.core.sched.interface import PauseState, SchedulerInterface
from vllm.v1.core.sched.output import (
CachedRequestData,
@@ -125,7 +126,9 @@ class Scheduler(SchedulerInterface):
self.connector = None
self.connector_prefix_cache_stats: PrefixCacheStats | None = None
self.recompute_kv_load_failures = True
if self.vllm_config.kv_transfer_config is not None:
self.defer_block_free = False
kv_transfer_config = self.vllm_config.kv_transfer_config
if kv_transfer_config is not None:
assert not self.is_encoder_decoder, (
"Encoder-decoder models are not currently supported with KV connectors"
)
@@ -136,11 +139,17 @@ class Scheduler(SchedulerInterface):
)
if self.log_stats:
self.connector_prefix_cache_stats = PrefixCacheStats()
kv_load_failure_policy = (
self.vllm_config.kv_transfer_config.kv_load_failure_policy
)
kv_load_failure_policy = kv_transfer_config.kv_load_failure_policy
self.recompute_kv_load_failures = kv_load_failure_policy == "recompute"
# With overlapping batches (async scheduling or PP), a step may
# still be writing a freed request's KV blocks. A consumer KV
# Connector can reallocate and fill those blocks via a load that
# isn't ordered against that write, so defer freeing them.
multiple_inflight_batches = self.vllm_config.max_concurrent_batches > 1
if multiple_inflight_batches and kv_transfer_config.is_kv_consumer:
self.defer_block_free = True
self.kv_event_publisher = EventPublisherFactory.create(
self.kv_events_config,
self.parallel_config.data_parallel_index,
@@ -275,6 +284,15 @@ class Scheduler(SchedulerInterface):
self.need_mamba_block_aligned_split = (
self.has_mamba_layers and self.cache_config.mamba_cache_mode == "align"
)
# Counts of non-empty steps scheduled / processed. update_from_output
# is called once per scheduled step in FIFO order, so these stay in sync.
self.sched_step_seq = 0
self.processed_step_seq = 0
# FIFO of (fence_seq, blocks): blocks become safe to free once
# processed_step_seq >= fence_seq.
self.deferred_frees: deque[tuple[int, list[KVCacheBlock]]] = deque()
self.perf_metrics: ModelMetrics | None = None
if self.log_stats and vllm_config.observability_config.enable_mfu_metrics:
self.perf_metrics = ModelMetrics(vllm_config)
@@ -1044,6 +1062,11 @@ class Scheduler(SchedulerInterface):
)
scheduler_output.ec_connector_metadata = ec_meta
# Advance the fence only for non-empty steps (those that actually
# write KV and have their output processed later in update_from_output).
if self.defer_block_free and total_num_scheduled_tokens > 0:
self.sched_step_seq += 1
with record_function_or_nullcontext("schedule: update_after_schedule"):
self._update_after_schedule(scheduler_output)
return scheduler_output
@@ -1062,7 +1085,7 @@ class Scheduler(SchedulerInterface):
assert request.status == RequestStatus.RUNNING, (
"Only running requests can be preempted"
)
self.kv_cache_manager.free(request)
self._free_request_blocks(request)
self.encoder_cache_manager.free(request)
self._inflight_prefills.discard(request)
request.status = RequestStatus.PREEMPTED
@@ -1090,6 +1113,9 @@ class Scheduler(SchedulerInterface):
for req_id, num_scheduled_token in num_scheduled_tokens.items():
request = self.requests[req_id]
request.num_computed_tokens += num_scheduled_token
if self.defer_block_free:
# Record the in-flight step, to fence deferred block freeing.
request.last_sched_seq = self.sched_step_seq
request.is_prefill_chunk = request.num_computed_tokens < (
request.num_tokens + request.num_output_placeholders
)
@@ -1422,6 +1448,12 @@ class Scheduler(SchedulerInterface):
kv_connector_output = model_runner_output.kv_connector_output
cudagraph_stats = model_runner_output.cudagraph_stats
# Every GPU write enqueued by this and earlier steps has completed, so it is
# safe to return deferred-free blocks to the pool.
if self.defer_block_free and scheduler_output.total_num_scheduled_tokens > 0:
self.processed_step_seq += 1
self._drain_deferred_frees()
perf_stats: PerfStats | None = None
if self.perf_metrics and self.perf_metrics.is_enabled():
perf_stats = self.perf_metrics.get_step_perf_stats_per_gpu(scheduler_output)
@@ -2006,7 +2038,7 @@ class Scheduler(SchedulerInterface):
def _free_blocks(self, request: Request):
assert request.is_finished()
self.kv_cache_manager.free(request)
self._free_request_blocks(request)
del self.requests[request.request_id]
@property
@@ -2016,6 +2048,35 @@ class Scheduler(SchedulerInterface):
def set_pause_state(self, pause_state: PauseState) -> None:
self._pause_state = pause_state
def _free_request_blocks(self, request: Request):
"""Free the request's KV blocks, deferring the return to the block
pool when an in-flight GPU step may still write them.
"""
if not self.defer_block_free or (
# Last scheduled step already processed: no in-flight write remains
# (always the case for a normal finish), so free now.
request.last_sched_seq <= self.processed_step_seq
):
self.kv_cache_manager.free(request)
return
blocks = self.kv_cache_manager.pop_blocks_for_free(request)
if blocks:
self.deferred_frees.append((self.sched_step_seq, blocks))
def _drain_deferred_frees(self):
"""Return deferred blocks whose fence step has completed.
Entries are appended with monotonically non-decreasing fences, so
stop at the first one that is still pending.
"""
while self.deferred_frees:
fence, _ = self.deferred_frees[0]
if fence > self.processed_step_seq:
break
_, blocks = self.deferred_frees.popleft()
# Free in reverse order so that the tail blocks are evicted first.
self.kv_cache_manager.block_pool.free_blocks(reversed(blocks))
def get_num_unfinished_requests(self) -> int:
if self._pause_state == PauseState.PAUSED_ALL:
return 0
+22 -11
View File
@@ -378,6 +378,24 @@ class SingleTypeKVCacheManager(ABC):
"""
return None
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
"""
Pop the request's bookkeeping and return its blocks without yet
returning them to the block pool. The caller is responsible for
eventually passing the returned blocks to `block_pool.free_blocks`,
freeing them in reverse order (so that tail blocks are evicted first).
Args:
request_id: The request ID.
Returns:
The request's blocks in allocation order.
"""
# Default to [] in case a request is freed (aborted) before alloc.
req_blocks = self.req_to_blocks.pop(request_id, [])
self.num_cached_block.pop(request_id, None)
return req_blocks
def free(self, request_id: str) -> None:
"""
Free the blocks for the request.
@@ -385,15 +403,8 @@ class SingleTypeKVCacheManager(ABC):
Args:
request_id: The request ID.
"""
# Default to [] in case a request is freed (aborted) before alloc.
req_blocks = self.req_to_blocks.pop(request_id, [])
# Free blocks in reverse order so that the tail blocks are
# freed first.
ordered_blocks = reversed(req_blocks)
self.block_pool.free_blocks(ordered_blocks)
self.num_cached_block.pop(request_id, None)
# Free blocks in reverse order so that the tail blocks are freed first.
self.block_pool.free_blocks(reversed(self.pop_blocks_for_free(request_id)))
@abstractmethod
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
@@ -1212,11 +1223,11 @@ class MambaManager(SingleTypeKVCacheManager):
self._allocated_block_reqs.add(request_id)
return req_blocks[prev_block_len:]
def free(self, request_id: str) -> None:
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
if self.mamba_cache_mode == "align":
self._allocated_block_reqs.discard(request_id)
self.last_state_block_idx.pop(request_id, None)
super().free(request_id)
return super().pop_blocks_for_free(request_id)
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
"""