[Bugfix][Pooling] Handle multimodal cache misses without crashing (#58975)

Signed-off-by: linchaoying6 <linchaoying6@jd.com>
Co-authored-by: linchaoying6 <linchaoying6@jd.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
Chaoying
2026-10-02 10:14:33 -04:00
committed by GitHub
co-authored by linchaoying6 OpenAI Codex
parent 443dccd3c9
commit 592c6f3fbc
21 changed files with 525 additions and 17 deletions
+5
View File
@@ -21,6 +21,7 @@ from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.engine.serving import BaseServing
from vllm.entrypoints.serve.engine.typing import AnyRequest
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
from vllm.exceptions import GenerationError, RetryableRequestError
from vllm.lora.request import LoRARequest
from vllm.renderers.base import BaseRenderer
from vllm.tracing import (
@@ -206,6 +207,10 @@ class PoolingBaseServing(ABC, BaseServing):
final_res_batch = [None] * num_inputs
async for i, res in ctx.result_generator:
if res.error is not None:
if res.error.retryable:
raise RetryableRequestError(res.error.message)
raise GenerationError(res.error.message)
final_res_batch[i] = res
if None in final_res_batch:
@@ -191,6 +191,27 @@ class ScoringIOProcessor(PoolingIOProcessor):
scoring_data = self.valid_inputs(data_1, data_2)
return scoring_data
def _pair_error_output(
self,
output_1: PoolingRequestOutput,
output_2: PoolingRequestOutput,
) -> PoolingRequestOutput | None:
failed = output_1 if output_1.error is not None else output_2
if failed.error is None:
return None
padding = [self.pad_token_id] if self.pad_token_id is not None else []
return PoolingRequestOutput(
request_id=f"{output_1.request_id}_{output_2.request_id}",
outputs=failed.outputs,
prompt_token_ids=(
output_1.prompt_token_ids + padding + output_2.prompt_token_ids
),
num_cached_tokens=(output_1.num_cached_tokens + output_2.num_cached_tokens),
finished=failed.finished,
error=failed.error,
)
class BiEncoderIOProcessor(ScoringIOProcessor):
name = "bi-encoder"
@@ -310,6 +331,10 @@ class BiEncoderIOProcessor(ScoringIOProcessor):
final_res_batch: list[PoolingRequestOutput] = []
for emb_1, emb_2 in zip(emb_data_1, emb_data_2):
if error_output := self._pair_error_output(emb_1, emb_2):
final_res_batch.append(error_output)
continue
pair_score = F.cosine_similarity(
emb_1.outputs.data.float(), emb_2.outputs.data.float(), dim=0
)
@@ -352,6 +377,10 @@ class LateInteractionIOProcessor(BiEncoderIOProcessor):
# Compute MaxSim scores
for emb_1, emb_2 in zip(emb_data_1, emb_data_2):
if error_output := self._pair_error_output(emb_1, emb_2):
final_res_batch.append(error_output)
continue
# emb_1.outputs.data: [query_len, dim]
# emb_2.outputs.data: [doc_len, dim]
q_emb = emb_1.outputs.data
@@ -907,6 +936,10 @@ class JinaRankingIOProcessor(LateInteractionIOProcessor, JinaRankingIOProcessorM
final_res_batch: list[PoolingRequestOutput] = []
for i in range(len(outputs)):
if outputs[i].error is not None:
final_res_batch.append(outputs[i])
continue
embeds = outputs[i].outputs.data.float()
# The JinaForRanking model concatenates docs first, then query.
+30 -5
View File
@@ -195,13 +195,36 @@ class ServingScores(PoolingServing):
ctx = await self._init_ctx(self.io_processor, *args, **kwargs)
await self._preprocessing(self.io_processor, ctx)
# stage 1: encode queries and cache token embeddings on workers.
await self._flash_late_interaction_encode_queries(ctx)
# stage 2: encode docs and return scalar scores from workers.
await self._flash_late_interaction_encode_docs(ctx)
try:
# stage 1: encode queries and cache token embeddings on workers.
await self._flash_late_interaction_encode_queries(ctx)
# stage 2: encode docs and return scalar scores from workers.
await self._flash_late_interaction_encode_docs(ctx)
except BaseException:
try:
await self._cleanup_flash_late_interaction(ctx)
except Exception:
logger.exception("Failed to clean up late-interaction query cache.")
raise
return await self._postprocessing_async(self.io_processor, ctx)
async def _cleanup_flash_late_interaction(self, ctx: ScoringServeContext) -> None:
query_keys = ctx.late_interaction_query_keys
if not query_keys:
return
doc_keys = ctx.late_interaction_doc_keys or []
try:
# Stop documents before removing the query tensors they reference.
await self.engine_client.abort([*query_keys, *doc_keys])
finally:
await self.engine_client.collective_rpc(
"release_late_interaction_query_cache",
args=(query_keys,),
)
async def _flash_late_interaction_encode_queries(self, ctx: ScoringServeContext):
assert ctx.n_queries is not None
assert ctx.engine_inputs is not None
@@ -259,7 +282,9 @@ class ServingScores(PoolingServing):
query_keys = ctx.late_interaction_query_keys
if query_keys is None:
raise RuntimeError("Late-interaction query keys were not initialized.")
doc_keys = [f"{ctx.request_id}-doc-{i}" for i in range(n_docs)]
doc_namespace = random_uuid()
doc_keys = [f"late-interaction-{doc_namespace}-doc-{i}" for i in range(n_docs)]
ctx.late_interaction_doc_keys = doc_keys
for i in range(n_docs):
query_idx = 0 if n_queries == 1 else i
+1
View File
@@ -115,6 +115,7 @@ class PoolingServeContext(Generic[PoolingRequestT]):
## for flash-late-interaction
query_final_res_batch: list[PoolingRequestOutput] | None = None
late_interaction_query_keys: list[str] | None = None
late_interaction_doc_keys: list[str] | None = None
@dataclass
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from http import HTTPStatus
from vllm.exceptions import GenerationError
from vllm.exceptions import GenerationError, RetryableRequestError
from vllm.logger import init_logger
from ..engine.protocol import ErrorInfo, ErrorResponse
@@ -56,7 +56,11 @@ def create_error_response(
status_code = HTTPStatus.BAD_REQUEST
param = None
elif isinstance(exc, GenerationError):
err_type = "InternalServerError"
err_type = (
"ServiceUnavailableError"
if isinstance(exc, RetryableRequestError)
else "InternalServerError"
)
status_code = exc.status_code
param = None
elif isinstance(exc, VLLMServerError):
@@ -70,8 +70,8 @@ async def generation_error_handler(req: Request, exc: GenerationError):
"""Handle GenerationError without logging stack traces.
GenerationError is a known, expected error (e.g. KV cache load failure)
that should be returned to the client as a 500 response without polluting
server logs with stack traces.
that should be returned to the client without polluting server logs with
stack traces.
"""
err = create_error_response(exc)
return JSONResponse(err.model_dump(), status_code=err.error.code)
+8
View File
@@ -130,6 +130,14 @@ class GenerationError(VLLMServerError):
self.status_code = HTTPStatus.INTERNAL_SERVER_ERROR
class RetryableRequestError(GenerationError):
"""A transient request-level failure that is safe for clients to retry."""
def __init__(self, message: str = "Request failed; please retry"):
super().__init__(message)
self.status_code = HTTPStatus.SERVICE_UNAVAILABLE
class GracefulHTTPError(VLLMError):
"""Exception that should be translated into an HTTP error response.
+37 -4
View File
@@ -18,6 +18,15 @@ from vllm.v1.metrics.stats import RequestSpecDecodeMetrics, RequestStateStats
logger = init_logger(__name__)
@dataclass(frozen=True)
class RequestError:
"""A request-level error that does not mark the engine as unhealthy."""
code: str
message: str
retryable: bool = False
@dataclass
class SamplingMask:
"""Per-token sampling support sets aligned with completion token IDs.
@@ -259,6 +268,7 @@ class PoolingRequestOutput(Generic[_O]):
prompt_token_ids (list[int]): A list of token IDs used in the prompt.
num_cached_tokens: The number of tokens with prefix cache hit.
finished (bool): A flag indicating whether the pooling is completed.
error: Structured request-level error information, if the request failed.
"""
@@ -269,20 +279,25 @@ class PoolingRequestOutput(Generic[_O]):
prompt_token_ids: list[int],
num_cached_tokens: int,
finished: bool,
*,
error: RequestError | None = None,
):
self.request_id = request_id
self.prompt_token_ids = prompt_token_ids
self.num_cached_tokens = num_cached_tokens
self.finished = finished
self.outputs = outputs
self.error = error
def __repr__(self) -> str:
error = f", error={self.error!r}" if self.error is not None else ""
return (
f"{type(self).__name__}(request_id={self.request_id!r}, "
f"outputs={self.outputs!r}, "
f"prompt_token_ids={self.prompt_token_ids}, "
f"num_cached_tokens={self.num_cached_tokens}, "
f"finished={self.finished})"
f"finished={self.finished}"
f"{error})"
)
@@ -319,12 +334,18 @@ class EmbeddingRequestOutput(PoolingRequestOutput[EmbeddingOutput]):
def from_base(
request_output: PoolingRequestOutput,
) -> "EmbeddingRequestOutput":
outputs = (
EmbeddingOutput([])
if request_output.error is not None
else EmbeddingOutput.from_base(request_output.outputs)
)
return EmbeddingRequestOutput(
request_id=request_output.request_id,
outputs=EmbeddingOutput.from_base(request_output.outputs),
outputs=outputs,
prompt_token_ids=request_output.prompt_token_ids,
num_cached_tokens=request_output.num_cached_tokens,
finished=request_output.finished,
error=request_output.error,
)
@@ -362,12 +383,18 @@ class ClassificationRequestOutput(PoolingRequestOutput[ClassificationOutput]):
def from_base(
request_output: PoolingRequestOutput,
) -> "ClassificationRequestOutput":
outputs = (
ClassificationOutput([])
if request_output.error is not None
else ClassificationOutput.from_base(request_output.outputs)
)
return ClassificationRequestOutput(
request_id=request_output.request_id,
outputs=ClassificationOutput.from_base(request_output.outputs),
outputs=outputs,
prompt_token_ids=request_output.prompt_token_ids,
num_cached_tokens=request_output.num_cached_tokens,
finished=request_output.finished,
error=request_output.error,
)
@@ -402,10 +429,16 @@ class ScoringRequestOutput(PoolingRequestOutput[ScoringOutput]):
def from_base(
request_output: PoolingRequestOutput,
) -> "ScoringRequestOutput":
outputs = (
ScoringOutput(0.0)
if request_output.error is not None
else ScoringOutput.from_base(request_output.outputs)
)
return ScoringRequestOutput(
request_id=request_output.request_id,
outputs=ScoringOutput.from_base(request_output.outputs),
outputs=outputs,
prompt_token_ids=request_output.prompt_token_ids,
num_cached_tokens=request_output.num_cached_tokens,
finished=request_output.finished,
error=request_output.error,
)
+8
View File
@@ -323,6 +323,14 @@ class LLMEngine:
engine_core_timestamp=outputs.timestamp,
iteration_stats=iteration_stats,
)
mm_processor_cache = self.renderer.mm_processor_cache
if mm_processor_cache is not None:
for engine_core_output in outputs.outputs:
if engine_core_output.mm_cache_miss_hashes:
for mm_hash in engine_core_output.mm_cache_miss_hashes:
mm_processor_cache.invalidate(mm_hash)
self.output_processor.update_scheduler_stats(outputs.scheduler_stats)
# 3) Abort any reqs that finished due to stop strings.
+19
View File
@@ -16,6 +16,7 @@ from vllm.outputs import (
CompletionOutput,
PoolingOutput,
PoolingRequestOutput,
RequestError,
RequestOutput,
SamplingMask,
)
@@ -304,6 +305,7 @@ class RequestState:
stop_reason: int | str | None,
kv_transfer_params: dict[str, Any] | None = None,
ec_transfer_params: dict[str, Any] | None = None,
error: RequestError | None = None,
) -> RequestOutput | PoolingRequestOutput | None:
finished = finish_reason is not None
final_only = self.output_kind == RequestOutputKind.FINAL_ONLY
@@ -342,6 +344,7 @@ class RequestState:
external_req_id,
[self._new_pooling_output(pooling_output)],
finished,
error=error,
)
output = self._new_completion_output(new_token_ids, finish_reason, stop_reason)
@@ -369,6 +372,7 @@ class RequestState:
finished: bool,
kv_transfer_params: dict[str, Any] | None = None,
ec_transfer_params: dict[str, Any] | None = None,
error: RequestError | None = None,
) -> RequestOutput | PoolingRequestOutput:
# If prompt embeds were used, put placeholder prompt token ids
prompt_token_ids = self.prompt_token_ids
@@ -385,6 +389,7 @@ class RequestState:
num_cached_tokens=self.num_cached_tokens,
prompt_token_ids=prompt_token_ids,
finished=finished,
error=error,
)
assert self.logprobs_processor is not None
if self.output_kind == RequestOutputKind.DELTA:
@@ -715,6 +720,19 @@ class OutputProcessor:
if engine_core_output.spec_decode_metrics is not None:
req_state.spec_decode_metrics = engine_core_output.spec_decode_metrics
request_error = None
if (
req_state.detokenizer is None
and engine_core_output.mm_cache_miss_hashes
and finish_reason == FinishReason.ERROR
):
request_error = RequestError(
code="multimodal_cache_miss",
message="Multi-modal processor cache miss.",
retryable=True,
)
pooling_output = EMPTY_CPU_TENSOR
if pooling_output is None:
assert req_state.detokenizer is not None
assert req_state.logprobs_processor is not None
@@ -742,6 +760,7 @@ class OutputProcessor:
stop_reason,
kv_transfer_params,
ec_transfer_params,
error=request_error,
):
if req_state.streaming_input:
request_output.finished = False
+12
View File
@@ -42,6 +42,18 @@ class LateInteractionRunner:
self._query_uses.clear()
self._doc_query_keys.clear()
def release_queries(self, query_keys: Iterable[str]) -> None:
query_keys = set(query_keys)
for query_key in query_keys:
self._query_cache.pop(query_key, None)
self._query_uses.pop(query_key, None)
self._doc_query_keys = {
req_id: query_key
for req_id, query_key in self._doc_query_keys.items()
if query_key not in query_keys
}
def register_request(
self, req_id: str, pooling_params: PoolingParams | None
) -> None:
+4
View File
@@ -1012,6 +1012,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
if self.pooling_runner is not None:
self.pooling_runner.clear()
def release_late_interaction_query_cache(self, query_keys: list[str]) -> None:
if self.pooling_runner is not None:
self.pooling_runner.release_late_interaction_query_cache(query_keys)
@torch.inference_mode()
def profile_cudagraph_memory(self) -> int:
"""Estimate the GPU memory required to capture CUDA graphs."""
@@ -98,6 +98,9 @@ class PoolingRunner:
def clear(self) -> None:
self.late_interaction_runner.clear()
def release_late_interaction_query_cache(self, query_keys: list[str]) -> None:
self.late_interaction_runner.release_queries(query_keys)
def _get_pooling_metadata(
self,
input_batch: InputBatch,
+3
View File
@@ -993,6 +993,9 @@ class GPUModelRunner(
self.encoder_cache.clear()
self.late_interaction_runner.clear()
def release_late_interaction_query_cache(self, query_keys: list[str]) -> None:
self.late_interaction_runner.release_queries(query_keys)
def _get_positions(self, num_tokens: Any):
if isinstance(num_tokens, int):
if self.uses_mrope:
+7
View File
@@ -143,6 +143,13 @@ class WorkerBase:
if callable(reset_fn):
reset_fn()
def release_late_interaction_query_cache(self, query_keys: list[str]) -> None:
release_fn = getattr(
self.model_runner, "release_late_interaction_query_cache", None
)
if callable(release_fn):
release_fn(query_keys)
def get_model(self) -> nn.Module:
raise NotImplementedError