[Bugfix][KV Connector] Fix SimpleCPUOffloadScheduler TOCTOU between Phase A and Phase B (#42289)
Signed-off-by: Qiuyang Yue <yueqiuyang1389@gmail.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: gemini-code-assist <noreply@google.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
gemini-code-assist
parent
3ca8db2ef8
commit
fab07e4d0f
@@ -131,6 +131,12 @@ class SimpleCPUOffloadScheduler:
|
||||
# the worker reports completions by event index, not request id.
|
||||
self._load_event_to_reqs: dict[int, list[str]] = {}
|
||||
|
||||
# Pending (cpu_hit_blocks, hit_length) tuples from find_longest_cache_hit,
|
||||
# kept pinned via touch() while awaiting update_state_after_alloc().
|
||||
self._pending_cpu_hits: dict[
|
||||
str, tuple[tuple[list[KVCacheBlock], ...], int]
|
||||
] = {}
|
||||
|
||||
# Store metadata
|
||||
self._lazy_mode = lazy_offload
|
||||
# Lazy mode: use a cursor to track the last scanned block in the GPU free queue.
|
||||
@@ -212,7 +218,17 @@ class SimpleCPUOffloadScheduler:
|
||||
def get_num_new_matched_tokens(
|
||||
self, request: "Request", num_computed_tokens: int
|
||||
) -> tuple[int | None, bool]:
|
||||
"""Return (num_new_tokens, is_async) from consecutive CPU cache hits."""
|
||||
"""Return (num_new_tokens, is_async) from consecutive CPU cache hits.
|
||||
|
||||
Pins found CPU blocks via touch() so they survive LRU eviction until
|
||||
update_state_after_alloc() consumes them. Any pin from an earlier
|
||||
call on the same request (e.g. retry after a failed allocate_slots)
|
||||
is dropped first.
|
||||
"""
|
||||
stale = self._pending_cpu_hits.pop(request.request_id, None)
|
||||
if stale is not None:
|
||||
self._free_pending_cpu_hit(stale)
|
||||
|
||||
skipped = num_computed_tokens // self.block_size
|
||||
remaining_hashes = request.block_hashes[skipped:]
|
||||
|
||||
@@ -223,11 +239,19 @@ class SimpleCPUOffloadScheduler:
|
||||
max_hit_len = request.num_tokens - 1 - num_computed_tokens
|
||||
if max_hit_len <= 0:
|
||||
return 0, False
|
||||
_, hit_length = self.cpu_coordinator.find_longest_cache_hit(
|
||||
cpu_hit_blocks, hit_length = self.cpu_coordinator.find_longest_cache_hit(
|
||||
remaining_hashes, max_hit_len
|
||||
)
|
||||
|
||||
if hit_length > 0:
|
||||
pin_blocks = [
|
||||
blk for grp in cpu_hit_blocks for blk in grp if not blk.is_null
|
||||
]
|
||||
self.cpu_block_pool.touch(pin_blocks)
|
||||
self._pending_cpu_hits[request.request_id] = (
|
||||
cpu_hit_blocks,
|
||||
hit_length,
|
||||
)
|
||||
return hit_length, True
|
||||
return 0, False
|
||||
|
||||
@@ -253,29 +277,60 @@ class SimpleCPUOffloadScheduler:
|
||||
num_stored_blocks=[0] * num_groups,
|
||||
)
|
||||
|
||||
# Pop the CPU hit cached by get_num_new_matched_tokens(). The
|
||||
# found blocks were pinned there to survive LRU eviction in the window
|
||||
# between get_num_new_matched_tokens() and this matching call.
|
||||
pending = self._pending_cpu_hits.pop(req_id, None)
|
||||
|
||||
if num_external_tokens == 0:
|
||||
if pending is not None:
|
||||
logger.warning(
|
||||
"SimpleCPUOffloadScheduler: update_state_after_alloc "
|
||||
"called for req_id=%s with no external tokens but "
|
||||
"get_num_new_matched_tokens() unexpectedly recorded "
|
||||
"a pending CPU hit; releasing the stale pin.",
|
||||
req_id,
|
||||
)
|
||||
self._free_pending_cpu_hit(pending)
|
||||
return
|
||||
|
||||
if pending is None:
|
||||
logger.warning(
|
||||
"SimpleCPUOffloadScheduler: update_state_after_alloc called "
|
||||
"for req_id=%s with num_external_tokens=%d but no pending "
|
||||
"CPU hit from get_num_new_matched_tokens(); skipping load.",
|
||||
req_id,
|
||||
num_external_tokens,
|
||||
)
|
||||
return
|
||||
|
||||
cpu_hit_blocks_full, _ = pending
|
||||
|
||||
num_blocks_to_load = num_external_tokens // self.block_size
|
||||
assert num_blocks_to_load > 0
|
||||
|
||||
skipped = sum(blk.block_hash is not None for blk in blocks.blocks[self.fa_gidx])
|
||||
num_computed_tokens = skipped * self.block_size
|
||||
hashes_to_load = request.block_hashes[skipped : skipped + num_blocks_to_load]
|
||||
|
||||
# Find CPU cached blocks across all groups.
|
||||
max_hit_len = len(hashes_to_load) * self.block_size
|
||||
cpu_hit_blocks, hit_length = self.cpu_coordinator.find_longest_cache_hit(
|
||||
hashes_to_load, max_hit_len
|
||||
)
|
||||
assert hit_length == num_external_tokens, (
|
||||
f"Expected {num_external_tokens} hit tokens, got {hit_length}"
|
||||
)
|
||||
|
||||
# Build transfer pairs across all groups.
|
||||
total_computed_tokens = num_computed_tokens + num_external_tokens
|
||||
kv_cache_groups = self.cpu_kv_cache_config.kv_cache_groups
|
||||
|
||||
# The scheduler may have accepted fewer blocks than
|
||||
# get_num_new_matched_tokens() reported.
|
||||
# (e.g. due to token budget in test_partial_gpu_prefix_plus_cpu_load).
|
||||
# Take only the leading N blocks per group matching num_external_tokens;
|
||||
# the rest will be released along with the temp pin below.
|
||||
cpu_hit_blocks: list[list[KVCacheBlock]] = []
|
||||
for g in range(num_groups):
|
||||
g_block_size = kv_cache_groups[g].kv_cache_spec.block_size
|
||||
assert num_external_tokens % g_block_size == 0, (
|
||||
f"num_external_tokens={num_external_tokens} not aligned to "
|
||||
f"group {g} block_size={g_block_size}"
|
||||
)
|
||||
n_take_g = num_external_tokens // g_block_size
|
||||
cpu_hit_blocks.append(cpu_hit_blocks_full[g][:n_take_g])
|
||||
|
||||
gpu_block_ids: list[int] = []
|
||||
cpu_block_ids: list[int] = []
|
||||
cpu_blocks_to_touch: list[KVCacheBlock] = []
|
||||
@@ -304,6 +359,8 @@ class SimpleCPUOffloadScheduler:
|
||||
|
||||
# Touch CPU blocks to prevent eviction during async load.
|
||||
self.cpu_block_pool.touch(cpu_blocks_to_touch)
|
||||
# Release the temporary pin held since get_num_new_matched_tokens().
|
||||
self._free_pending_cpu_hit(pending)
|
||||
|
||||
# Touch GPU blocks to prevent freeing during async load
|
||||
assert self._gpu_block_pool is not None
|
||||
@@ -666,6 +723,12 @@ class SimpleCPUOffloadScheduler:
|
||||
so the scheduler can free blocks immediately."""
|
||||
req_id = request.request_id
|
||||
|
||||
# Release any temp CPU hit pin from get_num_new_matched_tokens()
|
||||
# if request is canceled or preempted before update_state_after_alloc()
|
||||
pending = self._pending_cpu_hits.pop(req_id, None)
|
||||
if pending is not None:
|
||||
self._free_pending_cpu_hit(pending)
|
||||
|
||||
# Handle load: defer cleanup if load is in-flight
|
||||
load_state = self._reqs_to_load.get(req_id)
|
||||
if load_state is not None:
|
||||
@@ -692,6 +755,15 @@ class SimpleCPUOffloadScheduler:
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
return self.request_finished(request, block_ids=[])
|
||||
|
||||
def _free_pending_cpu_hit(self, pending: tuple) -> None:
|
||||
"""Release the temporary CPU block pin taken in get_num_new_matched_tokens()."""
|
||||
cpu_hit_blocks, _ = pending
|
||||
blocks_to_free = [
|
||||
blk for grp in cpu_hit_blocks for blk in grp if not blk.is_null
|
||||
]
|
||||
if blocks_to_free:
|
||||
self.cpu_block_pool.free_blocks(blocks_to_free)
|
||||
|
||||
def _cleanup_load_request(self, req_id: str) -> None:
|
||||
"""Release all load resources for a request.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user