[Bugfix][V1] Free out-of-window blocks on the processed-token basis under async scheduling (#47728)

Signed-off-by: Saddss <28726669061@qq.com>
Signed-off-by: Nick Hill <nickhill123@gmail.com>
Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai>
Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai>
Co-authored-by: Saddss <28726669061@qq.com>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
This commit is contained in:
Saddss
2026-07-08 13:34:19 +01:00
committed by GitHub
co-authored by Yifan Qiao Saddss Nick Hill
parent 934eeaecfb
commit cd0de48d08
14 changed files with 549 additions and 143 deletions
+11
View File
@@ -501,6 +501,17 @@ class VllmConfig:
return 2
return pp_size
@property
def max_in_flight_tokens(self) -> int:
# Upper bound on tokens that are scheduled but not yet settled (freed):
# every concurrent batch may hold up to a full `max_num_batched_tokens`.
# Recycling-aware KV cache specs (sliding-window, chunked-local) reserve
# for this because out-of-window blocks are freed on the processed-token
# basis, so in-flight steps transiently keep their blocks.
return (
self.max_concurrent_batches * self.scheduler_config.max_num_batched_tokens
)
@property
def num_speculative_tokens(self) -> int:
if (
+16 -16
View File
@@ -67,7 +67,7 @@ class KVCacheCoordinator(ABC):
self,
kv_cache_config: KVCacheConfig,
max_model_len: int,
max_num_batched_tokens: int,
max_in_flight_tokens: int,
use_eagle: bool,
enable_caching: bool,
enable_kv_cache_events: bool,
@@ -107,7 +107,7 @@ class KVCacheCoordinator(ABC):
self.single_type_managers = tuple(
get_manager_for_kv_cache_spec(
kv_cache_spec=kv_cache_group.kv_cache_spec,
max_num_batched_tokens=max_num_batched_tokens,
max_in_flight_tokens=max_in_flight_tokens,
max_model_len=max_model_len,
block_pool=self.block_pool,
enable_caching=enable_caching,
@@ -332,7 +332,7 @@ class KVCacheCoordinator(ABC):
def remove_skipped_blocks(
self,
request_id: str,
total_computed_tokens: int,
processed_computed_tokens: int,
num_prompt_tokens: int | None = None,
) -> None:
"""
@@ -341,15 +341,15 @@ class KVCacheCoordinator(ABC):
Args:
request_id: The request ID.
total_computed_tokens: The total number of computed tokens, including
local computed tokens and external computed tokens.
processed_computed_tokens: Computed-token prefix length covering
fully processed and committed tokens only (safe to free).
num_prompt_tokens: Optional prompt length. R-SWA managers use this to
free gap blocks between the prefill tail and decode window; other
manager types ignore it.
"""
for manager in self.single_type_managers:
manager.remove_skipped_blocks(
request_id, total_computed_tokens, num_prompt_tokens
request_id, processed_computed_tokens, num_prompt_tokens
)
def get_blocks(self, request_id: str) -> tuple[list[KVCacheBlock], ...]:
@@ -387,7 +387,7 @@ class KVCacheCoordinatorNoPrefixCache(KVCacheCoordinator):
self,
kv_cache_config: KVCacheConfig,
max_model_len: int,
max_num_batched_tokens: int,
max_in_flight_tokens: int,
use_eagle: bool,
enable_kv_cache_events: bool,
dcp_world_size: int,
@@ -399,7 +399,7 @@ class KVCacheCoordinatorNoPrefixCache(KVCacheCoordinator):
super().__init__(
kv_cache_config,
max_model_len,
max_num_batched_tokens,
max_in_flight_tokens,
use_eagle,
False,
enable_kv_cache_events,
@@ -436,7 +436,7 @@ class UnitaryKVCacheCoordinator(KVCacheCoordinator):
self,
kv_cache_config: KVCacheConfig,
max_model_len: int,
max_num_batched_tokens: int,
max_in_flight_tokens: int,
use_eagle: bool,
enable_caching: bool,
enable_kv_cache_events: bool,
@@ -449,7 +449,7 @@ class UnitaryKVCacheCoordinator(KVCacheCoordinator):
super().__init__(
kv_cache_config,
max_model_len,
max_num_batched_tokens,
max_in_flight_tokens,
use_eagle,
enable_caching,
enable_kv_cache_events,
@@ -522,7 +522,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
self,
kv_cache_config: KVCacheConfig,
max_model_len: int,
max_num_batched_tokens: int,
max_in_flight_tokens: int,
use_eagle: bool,
enable_caching: bool,
enable_kv_cache_events: bool,
@@ -535,7 +535,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
super().__init__(
kv_cache_config,
max_model_len,
max_num_batched_tokens,
max_in_flight_tokens,
use_eagle,
enable_caching,
enable_kv_cache_events,
@@ -783,7 +783,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
def get_kv_cache_coordinator(
kv_cache_config: KVCacheConfig,
max_model_len: int,
max_num_batched_tokens: int,
max_in_flight_tokens: int,
use_eagle: bool,
enable_caching: bool,
enable_kv_cache_events: bool,
@@ -797,7 +797,7 @@ def get_kv_cache_coordinator(
return KVCacheCoordinatorNoPrefixCache(
kv_cache_config,
max_model_len,
max_num_batched_tokens,
max_in_flight_tokens,
use_eagle,
enable_kv_cache_events,
dcp_world_size=dcp_world_size,
@@ -810,7 +810,7 @@ def get_kv_cache_coordinator(
return UnitaryKVCacheCoordinator(
kv_cache_config,
max_model_len,
max_num_batched_tokens,
max_in_flight_tokens,
use_eagle,
enable_caching,
enable_kv_cache_events,
@@ -823,7 +823,7 @@ def get_kv_cache_coordinator(
return HybridKVCacheCoordinator(
kv_cache_config,
max_model_len,
max_num_batched_tokens,
max_in_flight_tokens,
use_eagle,
enable_caching,
enable_kv_cache_events,
+12 -9
View File
@@ -114,7 +114,7 @@ class KVCacheManager:
max_model_len: int,
scheduler_block_size: int,
hash_block_size: int,
max_num_batched_tokens: int | None = None,
max_in_flight_tokens: int | None = None,
enable_caching: bool = True,
use_eagle: bool = False,
log_stats: bool = False,
@@ -128,8 +128,8 @@ class KVCacheManager:
# When unset, fall back to `max_model_len` so the recycling-aware cap
# collapses to the prior (uncapped) admission behavior. The scheduler
# always supplies the real value at runtime.
if max_num_batched_tokens is None:
max_num_batched_tokens = max_model_len
if max_in_flight_tokens is None:
max_in_flight_tokens = max_model_len
self.enable_caching = enable_caching
self.use_eagle = use_eagle
@@ -143,7 +143,7 @@ class KVCacheManager:
self.coordinator = get_kv_cache_coordinator(
kv_cache_config=kv_cache_config,
max_model_len=self.max_model_len,
max_num_batched_tokens=max_num_batched_tokens,
max_in_flight_tokens=max_in_flight_tokens,
use_eagle=self.use_eagle,
enable_caching=self.enable_caching,
enable_kv_cache_events=enable_kv_cache_events,
@@ -397,9 +397,12 @@ class KVCacheManager:
# insufficient free blocks.
# Should call this function before allocating new blocks to reduce
# the number of evicted blocks.
# Free on the processed-token basis: in-flight steps' attention windows
# still read blocks below the optimistic boundary, and rejected spec
# tokens can roll it back.
self.coordinator.remove_skipped_blocks(
request.request_id,
total_computed_tokens,
max(0, total_computed_tokens - request.num_in_flight_tokens),
num_prompt_tokens=request.num_prompt_tokens,
)
@@ -472,7 +475,7 @@ class KVCacheManager:
def remove_skipped_blocks(
self,
request_id: str,
total_computed_tokens: int,
processed_computed_tokens: int,
num_prompt_tokens: int | None = None,
) -> None:
"""Remove the blocks that are no longer needed from `blocks` and replace
@@ -480,12 +483,12 @@ class KVCacheManager:
Args:
request_id: The request ID.
total_computed_tokens: The total number of computed tokens, including
local computed tokens and external computed tokens.
processed_computed_tokens: Computed-token prefix length covering
fully processed and committed tokens only (safe to free).
num_prompt_tokens: Optional prompt length for R-SWA gap eviction.
"""
self.coordinator.remove_skipped_blocks(
request_id, total_computed_tokens, num_prompt_tokens
request_id, processed_computed_tokens, num_prompt_tokens
)
def pop_blocks_for_free(self, request: Request) -> list[KVCacheBlock]:
+9 -4
View File
@@ -262,7 +262,7 @@ class Scheduler(SchedulerInterface):
self.kv_cache_manager = KVCacheManager(
kv_cache_config=kv_cache_config,
max_model_len=self.max_model_len,
max_num_batched_tokens=self.scheduler_config.max_num_batched_tokens,
max_in_flight_tokens=vllm_config.max_in_flight_tokens,
enable_caching=self.cache_config.enable_prefix_caching,
use_eagle=self.use_eagle,
log_stats=self.log_stats,
@@ -1180,6 +1180,7 @@ 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
request.num_in_flight_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
@@ -1566,10 +1567,12 @@ class Scheduler(SchedulerInterface):
stopped_preempted_reqs: set[Request] = set()
for req_id, num_tokens_scheduled in num_scheduled_tokens.items():
assert num_tokens_scheduled > 0
request = self.requests.get(req_id)
if request is not None:
request.num_in_flight_tokens -= num_tokens_scheduled
if failed_kv_load_req_ids and req_id in failed_kv_load_req_ids:
# skip failed or rescheduled requests from KV load failure
continue
request = self.requests.get(req_id)
if request is None or request.is_finished():
# The request is already finished. This can happen if the
# request is aborted while the model is executing it (e.g.,
@@ -2367,10 +2370,12 @@ class Scheduler(SchedulerInterface):
return False, None
# Free any out-of-window prefix blocks before we hand the block table to
# the connector.
# the connector, on the processed-token basis (see `allocate_slots`).
self.kv_cache_manager.remove_skipped_blocks(
request_id=request.request_id,
total_computed_tokens=request.num_computed_tokens,
processed_computed_tokens=max(
0, request.num_computed_tokens - request.num_in_flight_tokens
),
num_prompt_tokens=request.num_prompt_tokens,
)
+17 -21
View File
@@ -508,7 +508,7 @@ class SingleTypeKVCacheManager(ABC):
def remove_skipped_blocks(
self,
request_id: str,
total_computed_tokens: int,
processed_computed_tokens: int,
num_prompt_tokens: int | None = None,
) -> None:
"""
@@ -520,15 +520,15 @@ class SingleTypeKVCacheManager(ABC):
Args:
request_id: The request ID.
total_computed_tokens: The total number of computed tokens, including
local computed tokens and external computed tokens.
processed_computed_tokens: Computed-token prefix length covering
fully processed and committed tokens only (safe to free).
num_prompt_tokens: Optional prompt length for attention types (e.g.
R-SWA) that evict a middle gap rather than a head prefix. Ignored
by the default implementation.
"""
del num_prompt_tokens
# Remove the blocks that will be skipped during attention computation.
num_skipped_tokens = self.get_num_skipped_tokens(total_computed_tokens)
num_skipped_tokens = self.get_num_skipped_tokens(processed_computed_tokens)
if num_skipped_tokens <= 0:
# This indicates that ALL tokens are inside attention window.
# Thus we do not need to free any blocks outside attention window.
@@ -639,14 +639,14 @@ class RSWAManager(FullAttentionManager):
def remove_skipped_blocks(
self,
request_id: str,
total_computed_tokens: int,
processed_computed_tokens: int,
num_prompt_tokens: int | None = None,
) -> None:
"""Free gap blocks that are no longer needed for attention.
Gap = blocks entirely within
[ceil(prefix_len / block_size) * block_size,
max(prefix_len, total_computed_tokens - rswa_window))
max(prefix_len, processed_computed_tokens - rswa_window))
Freed blocks are replaced with null_block in req_to_blocks so the
block_table passed to FA4 is valid (null_block KV is all-zero;
@@ -654,7 +654,7 @@ class RSWAManager(FullAttentionManager):
"""
if num_prompt_tokens is None:
super().remove_skipped_blocks(
request_id, total_computed_tokens, num_prompt_tokens
request_id, processed_computed_tokens, num_prompt_tokens
)
return
@@ -662,7 +662,9 @@ class RSWAManager(FullAttentionManager):
# First block fully after the prefill boundary.
first_gap_block = cdiv(num_prompt_tokens, bs)
# Decode window start position; blocks before this are evictable.
window_start = max(num_prompt_tokens, total_computed_tokens - self.rswa_window)
window_start = max(
num_prompt_tokens, processed_computed_tokens - self.rswa_window
)
last_gap_block = window_start // bs # exclusive upper bound
self._remove_blocks_in_range(request_id, first_gap_block, last_gap_block)
@@ -1144,20 +1146,13 @@ class MambaManager(SingleTypeKVCacheManager):
def remove_skipped_blocks(
self,
request_id: str,
num_computed_tokens: int,
processed_computed_tokens: int,
num_prompt_tokens: int | None = None,
) -> None:
assert isinstance(self.kv_cache_spec, MambaSpec)
# NOTE (tdoublep) with async scheduling, the num_computed_tokens can contain
# draft tokens from the previous step that may or may not be rejected later.
# This can make us think we are further ahead in the sequence than we actually
# are, so let's assume that all tokens are rejected so we don't free blocks
# that we might actually need.
num_computed_tokens = max(0, num_computed_tokens - self.num_speculative_blocks)
super().remove_skipped_blocks(
request_id, num_computed_tokens, num_prompt_tokens
request_id, processed_computed_tokens, num_prompt_tokens
)
if self.mamba_cache_mode == "align":
# `last_state_block_idx` refers to the block index allocated two steps ago.
@@ -1171,7 +1166,7 @@ class MambaManager(SingleTypeKVCacheManager):
if (
last_state_block_idx is not None
and last_state_block_idx
< cdiv(num_computed_tokens, self.block_size) - 1
< cdiv(processed_computed_tokens, self.block_size) - 1
):
blocks = self.req_to_blocks[request_id]
if blocks[last_state_block_idx] != self._null_block:
@@ -1455,7 +1450,7 @@ class SinkFullAttentionManager(FullAttentionManager):
def get_manager_for_kv_cache_spec(
kv_cache_spec: KVCacheSpec,
max_num_batched_tokens: int,
max_in_flight_tokens: int,
max_model_len: int,
**kwargs,
) -> SingleTypeKVCacheManager:
@@ -1468,7 +1463,8 @@ def get_manager_for_kv_cache_spec(
Args:
kv_cache_spec: The KVCacheSpec instance
max_num_batched_tokens: The maximum number of tokens in a batch
max_in_flight_tokens: The max tokens scheduled but not yet settled
(one batch per concurrent step); see `VllmConfig.max_in_flight_tokens`
max_model_len: The maximum context length the model could serve
Returns:
An instance of the appropriate SingleTypeKVCacheManager subclass
@@ -1489,7 +1485,7 @@ def get_manager_for_kv_cache_spec(
):
kwargs["max_admission_blocks_per_request"] = (
kv_cache_spec.max_admission_blocks_per_request(
max_num_batched_tokens=max_num_batched_tokens,
max_in_flight_tokens=max_in_flight_tokens,
max_model_len=max_model_len,
)
)
+18 -15
View File
@@ -482,25 +482,28 @@ class ChunkedLocalAttentionSpec(AttentionSpec):
attention_chunk_size: int
def max_admission_blocks_per_request(
self, max_num_batched_tokens: int, max_model_len: int
self, max_in_flight_tokens: int, max_model_len: int
) -> int:
"""Per-request admission cap, in blocks.
Single source of truth for both startup pool sizing
(`max_memory_usage_bytes`) and the runtime admission gate, so requests
admitted by startup can also be admitted at runtime.
`max_in_flight_tokens` is the max tokens scheduled but not yet settled
(one batch per concurrent step); see `VllmConfig.max_in_flight_tokens`.
"""
# During chunked prefill, we hold KV for at most one chunk window.
# During chunked prefill, we hold KV for at most one chunk window plus
# the in-flight tokens, since frees happen on the processed-token basis.
num_tokens = min(
self.attention_chunk_size + max_num_batched_tokens, max_model_len
self.attention_chunk_size + max_in_flight_tokens, max_model_len
)
return cdiv(num_tokens, self.block_size)
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
max_model_len = vllm_config.model_config.max_model_len
max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens
max_blocks = self.max_admission_blocks_per_request(
max_num_batched_tokens=max_num_batched_tokens, max_model_len=max_model_len
max_in_flight_tokens=vllm_config.max_in_flight_tokens,
max_model_len=vllm_config.model_config.max_model_len,
)
return max_blocks * self.page_size_bytes
@@ -544,7 +547,7 @@ class SlidingWindowSpec(AttentionSpec):
)
def max_admission_blocks_per_request(
self, max_num_batched_tokens: int, max_model_len: int
self, max_in_flight_tokens: int, max_model_len: int
) -> int:
"""Per-request admission cap, in blocks.
@@ -553,13 +556,14 @@ class SlidingWindowSpec(AttentionSpec):
real-held blocks plateau at this bound because
`SlidingWindowManager.remove_skipped_blocks` runs from `allocate_slots`
before each chunk's `get_num_blocks_to_allocate`.
`max_in_flight_tokens` is the max tokens scheduled but not yet settled
(one batch per concurrent step); see `VllmConfig.max_in_flight_tokens`.
"""
# During chunked prefill, we hold KV for the last `sliding_window-1`
# computed tokens plus the newly scheduled tokens, and never more
# than `max_model_len`.
num_tokens = min(
self.sliding_window - 1 + max_num_batched_tokens, max_model_len
)
# computed tokens plus the in-flight tokens (frees happen on the
# processed-token basis); never more than `max_model_len`.
num_tokens = min(self.sliding_window - 1 + max_in_flight_tokens, max_model_len)
# +1 because the sliding window may not start from the beginning of
# the block. E.g. block size 4 and num_token 4 needs two blocks
# [XXCD][EF] to store the 6-token window [CDEF].
@@ -569,10 +573,9 @@ class SlidingWindowSpec(AttentionSpec):
assert vllm_config.parallel_config.decode_context_parallel_size == 1, (
"DCP not support sliding window."
)
max_model_len = vllm_config.model_config.max_model_len
max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens
max_blocks = self.max_admission_blocks_per_request(
max_num_batched_tokens=max_num_batched_tokens, max_model_len=max_model_len
max_in_flight_tokens=vllm_config.max_in_flight_tokens,
max_model_len=vllm_config.model_config.max_model_len,
)
return max_blocks * self.page_size_bytes
+5
View File
@@ -141,6 +141,11 @@ class Request:
self.num_output_placeholders = 0
self.async_tokens_to_discard = 0
# Tokens of steps whose output is not yet processed (async scheduling
# and PP run ahead of the GPU); `num_computed_tokens` counts them
# optimistically.
self.num_in_flight_tokens = 0
# V2+PP+async: Enforces `pp_size` cadence between same-request decode steps
# so the worker's broadcast slot ring stays consistent.
self.next_decode_eligible_step = 0
+1 -3
View File
@@ -122,9 +122,7 @@ class SimpleCPUOffloadScheduler:
self.cpu_coordinator: KVCacheCoordinator = get_kv_cache_coordinator(
kv_cache_config=self.cpu_kv_cache_config,
max_model_len=vllm_config.model_config.max_model_len,
max_num_batched_tokens=(
vllm_config.scheduler_config.max_num_batched_tokens
),
max_in_flight_tokens=vllm_config.max_in_flight_tokens,
use_eagle=False,
enable_caching=True,
enable_kv_cache_events=self.enable_kv_cache_events,