[V1] [P/D] Add Support for KV Load Failure Recovery (#19330)
Signed-off-by: David Ben-David <davidb@pliops.com> Co-authored-by: David Ben-David <davidb@pliops.com>
This commit is contained in:
co-authored by
David Ben-David
parent
67f3fb0844
commit
9a9f48dff7
@@ -117,7 +117,7 @@ def get_kv_connector_cache_layout():
|
||||
|
||||
|
||||
class KVOutputAggregator:
|
||||
"""Utility class to aggregate the output of all workers into a single
|
||||
"""Utility class to aggregate the output of all workers into a single
|
||||
output corresponding to Rank 0 for scheduler."""
|
||||
|
||||
def __init__(self, world_size: int):
|
||||
@@ -143,6 +143,7 @@ class KVOutputAggregator:
|
||||
finished_sending = set[str]()
|
||||
finished_recving = set[str]()
|
||||
aggregated_kv_connector_stats = None
|
||||
invalid_block_ids = set[int]()
|
||||
for model_runner_output in outputs:
|
||||
output = model_runner_output.kv_connector_output
|
||||
if not output:
|
||||
@@ -165,6 +166,8 @@ class KVOutputAggregator:
|
||||
aggregated_kv_connector_stats = \
|
||||
aggregated_kv_connector_stats.aggregate(kv_connector_stats)
|
||||
|
||||
invalid_block_ids |= output.invalid_block_ids
|
||||
|
||||
# select output of the worker specified by output_rank
|
||||
output = outputs[output_rank]
|
||||
|
||||
@@ -172,6 +175,7 @@ class KVOutputAggregator:
|
||||
finished_sending=finished_sending or None,
|
||||
finished_recving=finished_recving or None,
|
||||
kv_connector_stats=aggregated_kv_connector_stats or None,
|
||||
invalid_block_ids=invalid_block_ids,
|
||||
)
|
||||
|
||||
return output
|
||||
|
||||
@@ -229,6 +229,26 @@ class KVConnectorBase_V1(ABC):
|
||||
"""
|
||||
return None, None
|
||||
|
||||
def get_block_ids_with_load_errors(self) -> set[int]:
|
||||
"""
|
||||
Get the set of block IDs that failed to load.
|
||||
|
||||
Returns:
|
||||
Set of block IDs that encountered load errors.
|
||||
Empty set if no load errors occurred.
|
||||
|
||||
Notes:
|
||||
- Applies to both sync- and async-loading requests.
|
||||
- Async loading: failed blocks may be reported in any forward pass
|
||||
up to and including the pass where the request ID is returned by
|
||||
`get_finished()`. Even if failures occur, the request must still
|
||||
be reported via `get_finished()`, and the failed block IDs must
|
||||
appear here no later than that same pass.
|
||||
- Sync loading: failed blocks should be reported in the forward
|
||||
pass in which they are detected.
|
||||
"""
|
||||
return set()
|
||||
|
||||
def shutdown(self):
|
||||
"""
|
||||
Shutdown the connector. This is called when the worker process
|
||||
@@ -264,14 +284,21 @@ class KVConnectorBase_V1(ABC):
|
||||
|
||||
Returns:
|
||||
A tuple with the following elements:
|
||||
- An optional number of tokens that can be loaded from the
|
||||
external KV cache beyond what is already computed.
|
||||
- An optional number of tokens that can be loaded from the
|
||||
external KV cache beyond what is already computed.
|
||||
If None, it means that the connector needs more time to
|
||||
determine the number of matched tokens, and the scheduler
|
||||
should query for this request again later.
|
||||
- `True` if external KV cache tokens will be loaded
|
||||
asynchronously (between scheduler steps). Must be
|
||||
'False' if the first element is 0.
|
||||
|
||||
Notes:
|
||||
The connector should only consider the largest prefix of prompt-
|
||||
tokens for which KV cache is actually available at the time of the
|
||||
call. If the cache cannot be loaded for some tokens (e.g., due to
|
||||
connectivity issues or eviction), those tokens must not be taken
|
||||
into account.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@@ -189,6 +189,12 @@ class MultiConnector(KVConnectorBase_V1):
|
||||
|
||||
return finished_sending or None, finished_recving or None
|
||||
|
||||
def get_block_ids_with_load_errors(self) -> set[int]:
|
||||
agg_block_ids: set[int] = set()
|
||||
for c in self._connectors:
|
||||
agg_block_ids |= c.get_block_ids_with_load_errors()
|
||||
return agg_block_ids
|
||||
|
||||
# ==============================
|
||||
# Scheduler-side methods
|
||||
# ==============================
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import hashlib
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, Optional
|
||||
|
||||
import safetensors
|
||||
@@ -55,10 +55,7 @@ class ReqMeta:
|
||||
|
||||
@dataclass
|
||||
class SharedStorageConnectorMetadata(KVConnectorMetadata):
|
||||
requests: list[ReqMeta]
|
||||
|
||||
def __init__(self):
|
||||
self.requests = []
|
||||
requests: list[ReqMeta] = field(default_factory=list)
|
||||
|
||||
def add_request(
|
||||
self,
|
||||
|
||||
@@ -211,7 +211,7 @@ class BlockPool:
|
||||
block_size: Number of tokens in each block.
|
||||
kv_cache_group_id: The id of the KV cache group.
|
||||
"""
|
||||
if num_cached_blocks == num_full_blocks:
|
||||
if num_cached_blocks >= num_full_blocks:
|
||||
return
|
||||
new_full_blocks = blocks[num_cached_blocks:num_full_blocks]
|
||||
assert len(request.block_hashes) >= num_full_blocks
|
||||
|
||||
@@ -101,6 +101,7 @@ class CachedRequestData:
|
||||
new_token_ids: list[list[int]]
|
||||
new_block_ids: list[Optional[tuple[list[int], ...]]]
|
||||
num_computed_tokens: list[int]
|
||||
num_output_tokens: list[int]
|
||||
|
||||
@property
|
||||
def num_reqs(self) -> int:
|
||||
@@ -114,6 +115,7 @@ class CachedRequestData:
|
||||
new_token_ids=[],
|
||||
new_block_ids=[],
|
||||
num_computed_tokens=[],
|
||||
num_output_tokens=[],
|
||||
)
|
||||
|
||||
|
||||
|
||||
+174
-14
@@ -133,6 +133,7 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
# KV Connector: requests in process of async KV loading or recving
|
||||
self.finished_recving_kv_req_ids: set[str] = set()
|
||||
self.failed_recving_kv_req_ids: set[str] = set()
|
||||
|
||||
# Encoder-related.
|
||||
# Calculate encoder cache size if applicable
|
||||
@@ -671,6 +672,7 @@ class Scheduler(SchedulerInterface):
|
||||
new_token_ids: list[list[int]] = []
|
||||
new_block_ids: list[Optional[tuple[list[int], ...]]] = []
|
||||
num_computed_tokens: list[int] = []
|
||||
num_output_tokens: list[int] = []
|
||||
|
||||
use_connector = self.connector is not None
|
||||
for req in itertools.chain(running_reqs, resumed_reqs):
|
||||
@@ -695,6 +697,7 @@ class Scheduler(SchedulerInterface):
|
||||
new_block_ids.append(
|
||||
req_to_new_blocks[req_id].get_block_ids(allow_none=True))
|
||||
num_computed_tokens.append(req.num_computed_tokens)
|
||||
num_output_tokens.append(len(req.output_token_ids))
|
||||
# Because resumed_reqs is usually empty, it is more efficient to do
|
||||
# in-place appending so that we don't need to allocate a new list.
|
||||
resumed_from_preemption = [False] * len(running_reqs)
|
||||
@@ -706,6 +709,7 @@ class Scheduler(SchedulerInterface):
|
||||
new_token_ids=new_token_ids,
|
||||
new_block_ids=new_block_ids,
|
||||
num_computed_tokens=num_computed_tokens,
|
||||
num_output_tokens=num_output_tokens,
|
||||
)
|
||||
|
||||
def _try_schedule_encoder_inputs(
|
||||
@@ -878,6 +882,14 @@ class Scheduler(SchedulerInterface):
|
||||
kv_connector_stats = (kv_connector_output.kv_connector_stats
|
||||
if kv_connector_output else None)
|
||||
|
||||
failed_kv_load_req_ids = None
|
||||
if kv_connector_output and kv_connector_output.invalid_block_ids:
|
||||
# These blocks contain externally computed tokens that failed to
|
||||
# load. Identify affected requests and adjust their computed token
|
||||
# count to trigger recomputation of the invalid blocks.
|
||||
failed_kv_load_req_ids = self._handle_invalid_blocks(
|
||||
kv_connector_output.invalid_block_ids)
|
||||
|
||||
# NOTE(woosuk): As len(num_scheduled_tokens) can be up to 1K or more,
|
||||
# the below loop can be a performance bottleneck. We should do our best
|
||||
# to avoid expensive operations inside the loop.
|
||||
@@ -885,6 +897,9 @@ 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
|
||||
if failed_kv_load_req_ids and req_id in failed_kv_load_req_ids:
|
||||
# Skip requests that were recovered from KV load failure
|
||||
continue
|
||||
request = self.requests.get(req_id)
|
||||
if request is None:
|
||||
# The request is already finished. This can happen if the
|
||||
@@ -988,9 +1003,8 @@ class Scheduler(SchedulerInterface):
|
||||
self.waiting.remove_requests(stopped_preempted_reqs)
|
||||
|
||||
# KV Connector: update state for finished KV Transfers.
|
||||
if model_runner_output.kv_connector_output:
|
||||
self._update_from_kv_xfer_finished(
|
||||
model_runner_output.kv_connector_output)
|
||||
if kv_connector_output:
|
||||
self._update_from_kv_xfer_finished(kv_connector_output)
|
||||
|
||||
# Create EngineCoreOutputs for all clients that have requests with
|
||||
# outputs in this step.
|
||||
@@ -1252,18 +1266,33 @@ class Scheduler(SchedulerInterface):
|
||||
if request.request_id not in self.finished_recving_kv_req_ids:
|
||||
return False
|
||||
|
||||
# Now that the blocks are ready, actually cache them.
|
||||
(block_ids, ) = self.kv_cache_manager.get_block_ids(request.request_id)
|
||||
num_computed_tokens = len(block_ids) * self.block_size
|
||||
# Handle the case where num request tokens less than one block.
|
||||
num_computed_tokens = min(num_computed_tokens, request.num_tokens)
|
||||
if num_computed_tokens == request.num_tokens:
|
||||
num_computed_tokens -= 1
|
||||
# This will cache the blocks iff caching is enabled.
|
||||
self.kv_cache_manager.cache_blocks(request, num_computed_tokens)
|
||||
if request.request_id in self.failed_recving_kv_req_ids:
|
||||
# Request had KV load failures; num_computed_tokens was already
|
||||
# updated in _update_requests_with_invalid_blocks
|
||||
if request.num_computed_tokens:
|
||||
# Cache any valid computed tokens.
|
||||
self.kv_cache_manager.cache_blocks(request,
|
||||
request.num_computed_tokens)
|
||||
else:
|
||||
# No valid computed tokens, release allocated blocks.
|
||||
# There may be a local cache hit on retry.
|
||||
self.kv_cache_manager.free(request)
|
||||
|
||||
# Update the request state for scheduling.
|
||||
request.num_computed_tokens = num_computed_tokens
|
||||
self.failed_recving_kv_req_ids.remove(request.request_id)
|
||||
else:
|
||||
# Now that the blocks are ready, actually cache them.
|
||||
(block_ids, ) = self.kv_cache_manager.get_block_ids(
|
||||
request.request_id)
|
||||
num_computed_tokens = len(block_ids) * self.block_size
|
||||
# Handle the case where num request tokens less than one block.
|
||||
num_computed_tokens = min(num_computed_tokens, request.num_tokens)
|
||||
if num_computed_tokens == request.num_tokens:
|
||||
num_computed_tokens -= 1
|
||||
# This will cache the blocks iff caching is enabled.
|
||||
self.kv_cache_manager.cache_blocks(request, num_computed_tokens)
|
||||
|
||||
# Update the request state for scheduling.
|
||||
request.num_computed_tokens = num_computed_tokens
|
||||
|
||||
# Return that we are ready.
|
||||
self.finished_recving_kv_req_ids.remove(request.request_id)
|
||||
@@ -1296,3 +1325,134 @@ class Scheduler(SchedulerInterface):
|
||||
"but the request is already freed.", req_id)
|
||||
else:
|
||||
self._free_blocks(self.requests[req_id])
|
||||
|
||||
def _update_requests_with_invalid_blocks(
|
||||
self, requests: Iterable[Request],
|
||||
invalid_block_ids: set[int]) -> tuple[set[str], int]:
|
||||
"""
|
||||
Identify and update requests affected by invalid KV cache blocks.
|
||||
|
||||
This method scans the given requests, detects those with invalid blocks
|
||||
and adjusts their `num_computed_tokens` to the longest valid prefix.
|
||||
For observability, it also accumulates the total number of tokens that
|
||||
will need to be recomputed across all affected requests.
|
||||
|
||||
Args:
|
||||
requests: The set of requests to scan for invalid blocks.
|
||||
invalid_block_ids: IDs of invalid blocks.
|
||||
|
||||
Returns:
|
||||
tuple:
|
||||
- affected_req_ids (set[str]): IDs of requests impacted by
|
||||
invalid blocks.
|
||||
- total_affected_tokens (int): Total number of tokens that must
|
||||
be recomputed across all affected requests (for observability).
|
||||
"""
|
||||
affected_req_ids: set[str] = set()
|
||||
total_affected_tokens = 0
|
||||
# If a block is invalid and shared by multiple requests in the batch,
|
||||
# these requests must be rescheduled, but only the first will recompute
|
||||
# it. This set tracks blocks already marked for recomputation.
|
||||
marked_invalid_block_ids: set[int] = set()
|
||||
for request in requests:
|
||||
is_affected = False
|
||||
marked_invalid_block = False
|
||||
req_id = request.request_id
|
||||
# TODO (davidb): add support for hybrid memory allocator
|
||||
(req_block_ids, ) = self.kv_cache_manager.get_block_ids(req_id)
|
||||
# We iterate only over blocks that may contain externally computed
|
||||
# tokens
|
||||
if request.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
|
||||
# Async loading. If num_computed_tokens is set it implies we
|
||||
# already processed some block failures for it in a prior step
|
||||
req_num_computed_tokens = (
|
||||
request.num_computed_tokens if req_id
|
||||
in self.failed_recving_kv_req_ids else len(req_block_ids) *
|
||||
self.block_size)
|
||||
else:
|
||||
# Sync loading. num_computed_tokens includes new tokens
|
||||
req_num_computed_tokens = request.num_cached_tokens
|
||||
|
||||
req_num_computed_blocks = (req_num_computed_tokens +
|
||||
self.block_size - 1) // self.block_size
|
||||
for idx, block_id in zip(range(req_num_computed_blocks),
|
||||
req_block_ids):
|
||||
|
||||
if block_id not in invalid_block_ids:
|
||||
continue
|
||||
|
||||
is_affected = True
|
||||
|
||||
if block_id in marked_invalid_block_ids:
|
||||
# This invalid block is shared with a previous request
|
||||
# and was already marked for recomputation.
|
||||
# This means this request can still consider this block
|
||||
# as computed when rescheduled.
|
||||
# Currently this only applies to sync loading; Async
|
||||
# loading does not yet support block sharing
|
||||
continue
|
||||
|
||||
marked_invalid_block_ids.add(block_id)
|
||||
|
||||
if marked_invalid_block:
|
||||
# This request has already marked an invalid block for
|
||||
# recomputation and updated its num_computed_tokens.
|
||||
continue
|
||||
|
||||
marked_invalid_block = True
|
||||
# Truncate the computed tokens at the first failed block
|
||||
request.num_computed_tokens = idx * self.block_size
|
||||
total_affected_tokens += (req_num_computed_tokens -
|
||||
request.num_computed_tokens)
|
||||
|
||||
if is_affected:
|
||||
if not marked_invalid_block:
|
||||
# All invalid blocks of this request are shared with
|
||||
# previous requests and will be recomputed by them.
|
||||
# Revert to considering only cached tokens as computed.
|
||||
# Currently this only applies to sync loading; Async
|
||||
# loading does not yet support block sharing
|
||||
total_affected_tokens += (request.num_computed_tokens -
|
||||
request.num_cached_tokens)
|
||||
request.num_computed_tokens = request.num_cached_tokens
|
||||
|
||||
affected_req_ids.add(request.request_id)
|
||||
|
||||
return (affected_req_ids, total_affected_tokens)
|
||||
|
||||
def _handle_invalid_blocks(self, invalid_block_ids: set[int]) -> set[str]:
|
||||
total_requests_to_reschedule = 0
|
||||
total_tokens_to_reschedule = 0
|
||||
|
||||
# --- Handle async KV loads (WAITING_FOR_REMOTE_KVS) ---
|
||||
async_load_reqs = (
|
||||
req for req in self.waiting
|
||||
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS)
|
||||
async_affected_req_ids, num_tokens_to_reschedule = (
|
||||
self._update_requests_with_invalid_blocks(async_load_reqs,
|
||||
invalid_block_ids))
|
||||
|
||||
total_requests_to_reschedule += len(async_affected_req_ids)
|
||||
total_tokens_to_reschedule += num_tokens_to_reschedule
|
||||
|
||||
# Mark requests with async KV load failures; they will be rescheduled
|
||||
# once loading completes
|
||||
self.failed_recving_kv_req_ids |= async_affected_req_ids
|
||||
|
||||
# --- Handle sync KV loads (running requests) ---
|
||||
sync_affected_req_ids, num_tokens_to_reschedule = (
|
||||
self._update_requests_with_invalid_blocks(self.running,
|
||||
invalid_block_ids))
|
||||
|
||||
total_requests_to_reschedule += len(sync_affected_req_ids)
|
||||
total_tokens_to_reschedule += num_tokens_to_reschedule
|
||||
|
||||
if total_requests_to_reschedule:
|
||||
logger.warning(
|
||||
"Recovered from KV load failure: "
|
||||
"%d request(s) rescheduled (%d tokens affected).",
|
||||
total_requests_to_reschedule, total_tokens_to_reschedule)
|
||||
|
||||
# Return the IDs of affected running requests to skip in
|
||||
# update_from_output.
|
||||
return sync_affected_req_ids
|
||||
|
||||
@@ -142,6 +142,9 @@ class SingleTypeKVCacheManager(ABC):
|
||||
num_cached_blocks = self.num_cached_block[request.request_id]
|
||||
num_full_blocks = num_tokens // self.block_size
|
||||
|
||||
if num_cached_blocks >= num_full_blocks:
|
||||
return
|
||||
|
||||
self.block_pool.cache_full_blocks(
|
||||
request=request,
|
||||
blocks=self.req_to_blocks[request.request_id],
|
||||
|
||||
+5
-2
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, NamedTuple, Optional, Union
|
||||
|
||||
import torch
|
||||
@@ -87,10 +87,13 @@ class KVConnectorOutput:
|
||||
finished_sending: Optional[set[str]] = None
|
||||
finished_recving: Optional[set[str]] = None
|
||||
kv_connector_stats: Optional["KVConnectorStats"] = None
|
||||
# IDs of externally computed KV blocks that failed to load.
|
||||
# Requests referencing these blocks should be rescheduled to recompute them.
|
||||
invalid_block_ids: set[int] = field(default_factory=set)
|
||||
|
||||
def is_empty(self):
|
||||
return (not self.finished_sending and not self.finished_recving
|
||||
and not self.kv_connector_stats)
|
||||
and not self.kv_connector_stats and not self.invalid_block_ids)
|
||||
|
||||
|
||||
# ModelRunnerOutput is serialized and sent to the scheduler process.
|
||||
|
||||
@@ -634,8 +634,10 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
|
||||
num_computed_tokens = req_data.num_computed_tokens[i]
|
||||
new_block_ids = req_data.new_block_ids[i]
|
||||
resumed_from_preemption = req_data.resumed_from_preemption[i]
|
||||
num_output_tokens = req_data.num_output_tokens[i]
|
||||
|
||||
# Update the cached states.
|
||||
|
||||
req_state.num_computed_tokens = num_computed_tokens
|
||||
|
||||
if not is_last_rank:
|
||||
@@ -653,6 +655,21 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
|
||||
elif num_new_tokens > 0:
|
||||
req_state.output_token_ids.extend(
|
||||
new_token_ids[-num_new_tokens:])
|
||||
elif num_output_tokens < len(req_state.output_token_ids):
|
||||
# Some output tokens were discarded due to a sync-KV-load
|
||||
# failure. Align the cached state.
|
||||
del req_state.output_token_ids[num_output_tokens:]
|
||||
|
||||
req_index = self.input_batch.req_id_to_index.get(req_id)
|
||||
if req_index is not None:
|
||||
old_end_idx = self.input_batch.num_tokens_no_spec[
|
||||
req_index]
|
||||
end_idx = self.input_batch.num_prompt_tokens[
|
||||
req_index] + num_output_tokens
|
||||
self.input_batch.num_tokens[req_index] = end_idx
|
||||
self.input_batch.num_tokens_no_spec[req_index] = end_idx
|
||||
self.input_batch.is_token_ids[req_index,
|
||||
end_idx:old_end_idx] = False
|
||||
|
||||
# Update the block IDs.
|
||||
if not resumed_from_preemption:
|
||||
|
||||
@@ -464,8 +464,7 @@ class Worker(WorkerBase):
|
||||
|
||||
# In case of PP with kv transfer, we need to pass through the
|
||||
# kv_connector_output
|
||||
if (not kv_connector_output.finished_sending
|
||||
and not kv_connector_output.finished_recving):
|
||||
if kv_connector_output.is_empty():
|
||||
return EMPTY_MODEL_RUNNER_OUTPUT
|
||||
|
||||
output = copy.copy(EMPTY_MODEL_RUNNER_OUTPUT)
|
||||
|
||||
@@ -75,8 +75,7 @@ class KVConnectorModelRunnerMixin:
|
||||
scheduler_output, wait_for_save=False) as kv_connector_output:
|
||||
pass
|
||||
|
||||
if (not kv_connector_output.finished_sending
|
||||
and not kv_connector_output.finished_recving):
|
||||
if kv_connector_output.is_empty():
|
||||
return EMPTY_MODEL_RUNNER_OUTPUT
|
||||
|
||||
output = copy.copy(EMPTY_MODEL_RUNNER_OUTPUT)
|
||||
@@ -120,6 +119,8 @@ class KVConnectorModelRunnerMixin:
|
||||
|
||||
output.finished_sending, output.finished_recving = (
|
||||
kv_connector.get_finished(scheduler_output.finished_req_ids))
|
||||
output.invalid_block_ids = (
|
||||
kv_connector.get_block_ids_with_load_errors())
|
||||
|
||||
output.kv_connector_stats = KVConnectorModelRunnerMixin.\
|
||||
get_kv_connector_stats()
|
||||
|
||||
Reference in New Issue
Block a user