[Frontend][Core] Standardize request error handling with VLLMError hierarchy (#49665)

Signed-off-by: Zach Zhu <zzqshu@126.com>
This commit is contained in:
Zach Zhu
2026-07-29 04:20:40 +00:00
committed by GitHub
parent f37f03db4a
commit 58f9659397
46 changed files with 370 additions and 248 deletions
+16 -20
View File
@@ -28,7 +28,6 @@ from vllm.engine.protocol import EngineClient
from vllm.entrypoints.chat_utils import load_chat_template
from vllm.entrypoints.launcher import serve_http
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.engine.protocol import GenerationError
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.elastic_ep.middleware import ScalingMiddleware
@@ -42,20 +41,15 @@ from vllm.entrypoints.serve.utils.api_utils import (
)
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
from vllm.entrypoints.serve.utils.server_utils import (
engine_error_handler,
exception_handler,
generation_error_handler,
get_uvicorn_log_config,
http_exception_handler,
lifespan,
log_response,
validation_exception_handler,
vllm_error_handler,
)
from vllm.exceptions import (
VLLMNotFoundError,
VLLMUnprocessableEntityError,
VLLMValidationError,
)
from vllm.exceptions import VLLMError
from vllm.logger import init_logger
from vllm.reasoning import ReasoningParserManager
from vllm.renderers.online_derenderer import OnlineDerenderer
@@ -67,7 +61,6 @@ from vllm.usage.usage_lib import UsageContext
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.utils.network_utils import is_valid_ipv6_address
from vllm.utils.system_utils import decorate_logs, set_ulimit
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm.version import __version__ as VLLM_VERSION
prometheus_multiproc_dir: tempfile.TemporaryDirectory
@@ -291,23 +284,26 @@ def build_app(
allow_headers=args.allowed_headers,
)
# Exception handlers are registered in four layers:
# 1. framework errors raised by FastAPI/Starlette
# 2. vLLM-specific errors dispatched via a single ``VLLMError`` handler
# 3. fallback handlers for raw exceptions not yet migrated to ``VLLMError``
# 4. the raw ``Exception`` handler as a safety net
# Registering specific exception types (rather than only ``Exception``)
# ensures they are handled by ``ExceptionMiddleware`` (inside the Prometheus
# middleware) rather than ``ServerErrorMiddleware`` (outside it), so their
# status codes are recorded correctly.
app.exception_handler(HTTPException)(http_exception_handler)
app.exception_handler(RequestValidationError)(validation_exception_handler)
app.exception_handler(EngineGenerateError)(engine_error_handler)
app.exception_handler(EngineDeadError)(engine_error_handler)
app.exception_handler(GenerationError)(generation_error_handler)
# Register specific exception types so they are handled by
# ExceptionMiddleware (inside the Prometheus middleware) rather than
# ServerErrorMiddleware (outside it). Without this, these exceptions
# propagate through Prometheus as unhandled and get recorded as 5xx
# even though they result in 4xx responses to the client.
app.exception_handler(VLLMValidationError)(exception_handler)
app.exception_handler(VLLMUnprocessableEntityError)(exception_handler)
app.exception_handler(VLLMNotFoundError)(exception_handler)
app.exception_handler(VLLMError)(vllm_error_handler)
# TODO(zqzten): remove these fallback handlers after migration to VLLMError
app.exception_handler(ValueError)(exception_handler)
app.exception_handler(TypeError)(exception_handler)
app.exception_handler(OverflowError)(exception_handler)
app.exception_handler(NotImplementedError)(exception_handler)
app.exception_handler(Exception)(exception_handler)
# Ensure --api-key option from CLI takes precedence over VLLM_API_KEY
+2 -2
View File
@@ -19,7 +19,7 @@ from pydantic import (
from vllm.config.utils import replace
from vllm.entrypoints.chat_utils import make_tool_call_id
from vllm.exceptions import VLLMValidationError
from vllm.exceptions import VLLMServerError, VLLMValidationError
from vllm.logger import init_logger
from vllm.sampling_params import StructuredOutputsParams
from vllm.utils import random_uuid
@@ -404,7 +404,7 @@ class DeltaMessage(OpenAIBaseModel):
return data
class GenerationError(Exception):
class GenerationError(VLLMServerError):
"""raised when finish_reason indicates internal server error (500)"""
def __init__(self, message: str = "Internal server error"):
+18 -5
View File
@@ -28,7 +28,9 @@ def create_error_response(
)
from vllm.exceptions import (
VLLMClientError,
VLLMNotFoundError,
VLLMServerError,
VLLMUnprocessableEntityError,
VLLMValidationError,
)
@@ -45,8 +47,23 @@ def create_error_response(
err_type = "NotFoundError"
status_code = HTTPStatus.NOT_FOUND
param = None
elif isinstance(exc, VLLMClientError):
# Any other client-caused error defaults to 400.
err_type = "BadRequestError"
status_code = HTTPStatus.BAD_REQUEST
param = None
elif isinstance(exc, GenerationError):
err_type = "InternalServerError"
status_code = exc.status_code
param = None
elif isinstance(exc, VLLMServerError):
# Any other server-caused error defaults to 500.
err_type = "InternalServerError"
status_code = HTTPStatus.INTERNAL_SERVER_ERROR
param = None
# Fallback for raw exceptions not yet migrated to VLLMError.
# TODO(zqzten): remove these fallback handlers after migration to VLLMError
elif isinstance(exc, (ValueError, TypeError, OverflowError)):
# Common validation errors from user input
err_type = "BadRequestError"
status_code = HTTPStatus.BAD_REQUEST
param = None
@@ -54,10 +71,6 @@ def create_error_response(
err_type = "NotImplementedError"
status_code = HTTPStatus.NOT_IMPLEMENTED
param = None
elif isinstance(exc, GenerationError):
err_type = "InternalServerError"
status_code = exc.status_code
param = None
elif any(cls.__name__ == "TemplateError" for cls in type(exc).__mro__):
# jinja2.TemplateError and its subclasses (avoid importing jinja2)
err_type = "BadRequestError"
+11 -1
View File
@@ -31,7 +31,7 @@ from vllm.entrypoints.serve.utils.error_response import (
create_error_response,
sanitize_message,
)
from vllm.exceptions import VLLMValidationError
from vllm.exceptions import VLLMError, VLLMValidationError
from vllm.logger import init_logger
from vllm.utils.gc_utils import freeze_gc_heap
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
@@ -325,6 +325,16 @@ async def log_response(request: Request, call_next):
return response
async def vllm_error_handler(req: Request, exc: VLLMError):
"""Dispatch a vLLM-specific error to the appropriate handler."""
if isinstance(exc, (EngineGenerateError, EngineDeadError)):
return await engine_error_handler(req, exc)
elif isinstance(exc, GenerationError):
return await generation_error_handler(req, exc)
else:
return await exception_handler(req, exc)
async def engine_error_handler(
req: Request, exc: EngineDeadError | EngineGenerateError
):
+21 -3
View File
@@ -6,7 +6,25 @@
from typing import Any
class VLLMValidationError(ValueError):
class VLLMError(Exception):
"""Base class for all vLLM-specific errors.
Subclasses are split into `VLLMClientError` (caused by the request, mapped
to 4xx) and `VLLMServerError` (caused by the server, mapped to 5xx).
Dispatching on this hierarchy lets the entrypoints decide the HTTP status
without relying on raw Python exception types such as `ValueError`.
"""
class VLLMClientError(VLLMError):
"""Base class for errors caused by the client request (4xx)."""
class VLLMServerError(VLLMError):
"""Base class for errors caused by the server (5xx)."""
class VLLMValidationError(VLLMClientError):
"""vLLM-specific validation error for request validation failures.
Args:
@@ -36,7 +54,7 @@ class VLLMValidationError(ValueError):
return f"{base} ({', '.join(extras)})" if extras else base
class VLLMNotFoundError(Exception):
class VLLMNotFoundError(VLLMClientError):
"""vLLM-specific NotFoundError"""
pass
@@ -66,7 +84,7 @@ class LoRAAdapterNotFoundError(VLLMNotFoundError):
return self.message
class VLLMUnprocessableEntityError(ValueError):
class VLLMUnprocessableEntityError(VLLMClientError):
"""vLLM-specific error for unprocessable entity requests.
This exception is raised when the request content is invalid or cannot be
+4 -2
View File
@@ -7,6 +7,8 @@ from typing import TYPE_CHECKING, Literal, TypeAlias
from typing_extensions import NotRequired, TypedDict, assert_never
from vllm.exceptions import VLLMValidationError
if TYPE_CHECKING:
import torch
@@ -284,7 +286,7 @@ which can be passed to `LLMEngine.add_request` or `AsyncLLM.add_request`.
def _validate_enc_input(enc_input: SingletonInput) -> EncoderInput:
if enc_input["type"] == "embeds":
raise ValueError(
raise VLLMValidationError(
"Embedding inputs are not supported for encoder-decoder models"
)
@@ -302,7 +304,7 @@ def _validate_enc_input(enc_input: SingletonInput) -> EncoderInput:
def _validate_dec_input(dec_input: SingletonInput) -> DecoderEngineInput:
if dec_input["type"] == "embeds":
raise ValueError(
raise VLLMValidationError(
"Embedding inputs are not supported for encoder-decoder models"
)
+7 -6
View File
@@ -7,6 +7,7 @@ from typing import Any
import msgspec
from vllm.config import ModelConfig, PoolerConfig
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.sampling_params import RequestOutputKind
from vllm.tasks import PoolingTask, check_removed_pooling_task
@@ -145,7 +146,7 @@ class PoolingParams(
invalid_parameters.append(k)
if invalid_parameters:
raise ValueError(
raise VLLMValidationError(
f"Task {self.task} only supports {valid_parameters} "
f"parameters, does not support "
f"{invalid_parameters} parameters"
@@ -170,21 +171,21 @@ class PoolingParams(
valid_range = f"[1, {embedding_size}]"
dimensions_in_range = 1 <= dimensions <= embedding_size
if not model_config.is_matryoshka:
raise ValueError(
raise VLLMValidationError(
f"Model {model_name!r} does not support Matryoshka "
f"embeddings; dimensions must be unset "
f"(received dimensions={dimensions})."
)
if not dimensions_in_range:
raise ValueError(
raise VLLMValidationError(
f"Model {model_name!r} only supports dimensions in "
f"range {valid_range}, got {dimensions}."
)
mds = model_config.matryoshka_dimensions
if mds is not None and dimensions not in mds:
raise ValueError(
raise VLLMValidationError(
f"Model {model_name!r} only supports Matryoshka "
f"dimensions {str(mds)}, got {dimensions}."
)
@@ -208,7 +209,7 @@ class PoolingParams(
invalid_parameters.append(k)
if invalid_parameters:
raise ValueError(
raise VLLMValidationError(
f"Task {self.task!r} only supports {valid_parameters} "
f"parameters, does not support "
f"{invalid_parameters} parameters"
@@ -231,7 +232,7 @@ class PoolingParams(
def __post_init__(self) -> None:
check_removed_pooling_task(self.task)
if self.output_kind != RequestOutputKind.FINAL_ONLY:
raise ValueError(
raise VLLMValidationError(
"For pooling output_kind has to be FINAL_ONLY, "
f"got {self.output_kind!r}"
)
+40 -32
View File
@@ -100,12 +100,12 @@ class StructuredOutputsParams:
]
)
if count > 1:
raise ValueError(
raise VLLMValidationError(
"You can only use one kind of structured outputs constraint "
f"but multiple are specified: {self.__dict__}"
)
if count < 1:
raise ValueError(
raise VLLMValidationError(
"You must use one kind of structured outputs constraint "
f"but none are specified: {self.__dict__}"
)
@@ -166,13 +166,13 @@ class RepetitionDetectionParams:
or self.min_pattern_size < 0
or self.min_pattern_size > self.max_pattern_size
):
raise ValueError(
raise VLLMValidationError(
"max_pattern_size, min_pattern_size must be >=0, "
"with min_pattern_size <= max_pattern_size. "
"Set both to 0 to disable repetitive pattern detection."
)
if self.max_pattern_size > 0 and self.min_count < 2:
raise ValueError(
raise VLLMValidationError(
"min_count must be >= 2 to detect repetitive patterns "
"in engine output. If you do not wish to detect repetitive "
"patterns, set max_pattern_size to 0."
@@ -514,31 +514,33 @@ class SamplingParams(
def _verify_args(self) -> None:
if not isinstance(self.n, int):
raise ValueError(f"n must be an int, but is of type {type(self.n)}")
raise VLLMValidationError(
f"n must be an int, but is of type {type(self.n)}"
)
if self.n < 1:
raise ValueError(f"n must be at least 1, got {self.n}.")
raise VLLMValidationError(f"n must be at least 1, got {self.n}.")
max_n = envs.VLLM_MAX_N_SEQUENCES
if self.n > max_n:
raise ValueError(
raise VLLMValidationError(
f"n must be at most {max_n}, got {self.n}. "
"To increase this limit, set the VLLM_MAX_N_SEQUENCES "
"environment variable."
)
if not -2.0 <= self.presence_penalty <= 2.0:
raise ValueError(
raise VLLMValidationError(
f"presence_penalty must be in [-2, 2], got {self.presence_penalty}."
)
if not -2.0 <= self.frequency_penalty <= 2.0:
raise ValueError(
raise VLLMValidationError(
f"frequency_penalty must be in [-2, 2], got {self.frequency_penalty}."
)
if not math.isfinite(self.repetition_penalty):
raise ValueError(
raise VLLMValidationError(
"repetition_penalty must be a finite number, "
f"got {self.repetition_penalty}."
)
if self.repetition_penalty <= 0.0:
raise ValueError(
raise VLLMValidationError(
"repetition_penalty must be greater than zero, got "
f"{self.repetition_penalty}."
)
@@ -568,15 +570,15 @@ class SamplingParams(
)
# quietly accept -1 as disabled, but prefer 0
if self.top_k < -1:
raise ValueError(
raise VLLMValidationError(
f"top_k must be 0 (disable), or at least 1, got {self.top_k}."
)
if not isinstance(self.top_k, int):
raise TypeError(
raise VLLMValidationError(
f"top_k must be an integer, got {type(self.top_k).__name__}"
)
if not 0.0 <= self.min_p <= 1.0:
raise ValueError(f"min_p must be in [0, 1], got {self.min_p}.")
raise VLLMValidationError(f"min_p must be in [0, 1], got {self.min_p}.")
if self.max_tokens is not None and self.max_tokens < 1:
raise VLLMValidationError(
f"max_tokens must be at least 1, got {self.max_tokens}.",
@@ -584,11 +586,11 @@ class SamplingParams(
value=self.max_tokens,
)
if self.min_tokens < 0:
raise ValueError(
raise VLLMValidationError(
f"min_tokens must be greater than or equal to 0, got {self.min_tokens}."
)
if self.max_tokens is not None and self.min_tokens > self.max_tokens:
raise ValueError(
raise VLLMValidationError(
f"min_tokens must be less than or equal to "
f"max_tokens={self.max_tokens}, got {self.min_tokens}."
)
@@ -617,27 +619,29 @@ class SamplingParams(
)
assert isinstance(self.stop_token_ids, list)
if not all(isinstance(st_id, int) for st_id in self.stop_token_ids):
raise ValueError(
raise VLLMValidationError(
f"stop_token_ids must contain only integers, got {self.stop_token_ids}."
)
assert isinstance(self.stop, list)
if any(not stop_str for stop_str in self.stop):
raise ValueError("stop cannot contain an empty string.")
raise VLLMValidationError("stop cannot contain an empty string.")
if self.stop and not self.detokenize:
raise ValueError(
raise VLLMValidationError(
"stop strings are only supported when detokenize is True. "
"Set detokenize=True to use stop."
)
assert isinstance(self.bad_words, list)
if any(not bad_word for bad_word in self.bad_words):
raise ValueError(
raise VLLMValidationError(
f"bad_words cannot contain an empty string. "
f"Got bad_words={self.bad_words}"
)
def _verify_greedy_sampling(self) -> None:
if self.n > 1:
raise ValueError(f"n must be 1 when using greedy sampling, got {self.n}.")
raise VLLMValidationError(
f"n must be 1 when using greedy sampling, got {self.n}."
)
def update_from_generation_config(
self,
@@ -889,7 +893,7 @@ class SamplingParams(
# Some sampling parameters are not yet compatible with spec decoding.
if self.min_p > _SAMPLING_EPS or self.logit_bias:
raise ValueError(
raise VLLMValidationError(
"The min_p and logit_bias sampling parameters "
"are not yet supported with speculative decoding."
)
@@ -910,7 +914,7 @@ class SamplingParams(
or self.bad_words
or self.allowed_token_ids
):
raise ValueError(
raise VLLMValidationError(
"The temperature, min_p, seed, min_tokens, logit_bias, "
"bad_words, and allowed_token_ids sampling parameters "
"are not yet supported with diffusion models."
@@ -930,7 +934,7 @@ class SamplingParams(
# rather than sampling left-to-right, which the grammar FSM
# requires. Without this check, requests fail mid-generation
# with an FSM rejection (HTTP 500). See issue #45436.
raise ValueError(
raise VLLMValidationError(
"Structured outputs are not yet supported for diffusion "
"language models. Remove the structured output constraint "
"(e.g. `response_format`, `structured_outputs`) from the "
@@ -938,7 +942,7 @@ class SamplingParams(
)
if tokenizer is None:
raise ValueError(
raise VLLMValidationError(
"Structured outputs requires a tokenizer so it can't be used with 'skip_tokenizer_init'" # noqa: E501
)
@@ -952,7 +956,7 @@ class SamplingParams(
if backend != _backend and not (
backend == "auto" and self.structured_outputs._backend_was_auto
):
raise ValueError(
raise VLLMValidationError(
"Request-level structured output backend selection is not "
f"supported. The request specified '{_backend}', but vLLM "
f"was initialised with '{backend}'. This error can be "
@@ -967,7 +971,7 @@ class SamplingParams(
and not self.structured_outputs.choice
):
# It is invalid for choice to be an empty list
raise ValueError(
raise VLLMValidationError(
f"Choice '{self.structured_outputs.choice}' cannot be an empty list" # noqa: E501
)
# Reject empty string grammar early to avoid engine-side crashes
@@ -975,16 +979,20 @@ class SamplingParams(
isinstance(self.structured_outputs.grammar, str)
and self.structured_outputs.grammar.strip() == ""
):
raise ValueError("structured_outputs.grammar cannot be an empty string")
raise VLLMValidationError(
"structured_outputs.grammar cannot be an empty string"
)
# Reject empty string json schema early to avoid engine-side crashes
if (
isinstance(self.structured_outputs.json, str)
and self.structured_outputs.json.strip() == ""
):
raise ValueError("structured_outputs.json cannot be an empty string")
raise VLLMValidationError(
"structured_outputs.json cannot be an empty string"
)
# Reject json_object=False early to avoid engine-side crashes
if self.structured_outputs.json_object is False:
raise ValueError(
raise VLLMValidationError(
"structured_outputs.json_object must be True if set; omit "
"structured_outputs to disable structured outputs"
)
@@ -1006,7 +1014,7 @@ class SamplingParams(
validate_xgrammar_grammar(self)
elif backend.startswith("guidance"):
if _is_non_tekken_mistral(tokenizer=tokenizer):
raise ValueError(
raise VLLMValidationError(
"Non-tekken Mistral tokenizers are not supported for the 'guidance'"
" structured output backend. Please either use a more recent "
"Mistral model, the ['xgrammar', 'outlines'] "
@@ -1026,7 +1034,7 @@ class SamplingParams(
elif backend == "lm-format-enforcer":
# lm format enforcer backend
if is_mistral_tokenizer(tokenizer):
raise ValueError(
raise VLLMValidationError(
"Mistral tokenizer is not supported for the 'lm-format-enforcer' "
"structured output backend. Please use ['xgrammar', 'outlines'] "
"backends or tokenizer_mode='hf' instead."
+6 -5
View File
@@ -21,6 +21,7 @@ from vllm.distributed.weight_transfer.base import (
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.engine.protocol import EngineClient, StreamingInput
from vllm.entrypoints.serve.elastic_ep.middleware import set_scaling_elastic_ep
from vllm.exceptions import VLLMClientError, VLLMValidationError
from vllm.inputs import EngineInput, PromptType
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
@@ -309,7 +310,7 @@ class AsyncLLM(EngineClient):
and not is_pooling
and params.prompt_logprobs
):
raise ValueError(
raise VLLMValidationError(
"--kv-sharing-fast-prefill produces incorrect logprobs for "
"prompt tokens, please disable it when the requests need "
"prompt logprobs"
@@ -476,7 +477,7 @@ class AsyncLLM(EngineClient):
)
req.external_req_id = request_id
if req.prompt_embeds is not None:
raise ValueError(
raise VLLMValidationError(
"prompt_embeds not supported for streaming inputs"
)
prompt_text, _, _ = extract_prompt_components(
@@ -512,7 +513,7 @@ class AsyncLLM(EngineClient):
or params.output_kind == RequestOutputKind.FINAL_ONLY
or params.stop
):
raise ValueError(
raise VLLMValidationError(
"Input streaming not currently supported "
"for pooling models, n > 1, request_kind = FINAL_ONLY "
"or with stop strings."
@@ -604,7 +605,7 @@ class AsyncLLM(EngineClient):
raise
# Request validation error.
except ValueError as e:
except VLLMClientError as e:
if self.log_requests:
logger.info("Request %s failed (bad request): %s.", request_id, e)
raise
@@ -869,7 +870,7 @@ class AsyncLLM(EngineClient):
raise
# Request validation error.
except ValueError:
except VLLMClientError:
if self.log_requests:
logger.info("Request %s failed (bad request).", request_id)
raise
+5 -2
View File
@@ -1,12 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
class EngineGenerateError(Exception):
from vllm.exceptions import VLLMServerError
class EngineGenerateError(VLLMServerError):
"""Raised when a AsyncLLM.generate() fails. Recoverable."""
pass
class EngineDeadError(Exception):
class EngineDeadError(VLLMServerError):
"""Raised when the EngineCore dies. Unrecoverable."""
def __init__(self, *args, suppress_context: bool = False, **kwargs):
+15 -12
View File
@@ -7,6 +7,7 @@ from typing import Any, Literal
import vllm.envs as envs
from vllm.config import VllmConfig
from vllm.exceptions import VLLMValidationError
from vllm.inputs import (
EngineInput,
PromptType,
@@ -90,7 +91,7 @@ class InputProcessor:
task for task in supported_tasks if task in GENERATION_TASKS
]
if not supported_generation_tasks:
raise ValueError("This model does not support generation")
raise VLLMValidationError("This model does not support generation")
params.verify(
self.model_config,
@@ -104,13 +105,13 @@ class InputProcessor:
self.vllm_config.reasoning_config is None
or not self.vllm_config.reasoning_config.enabled
):
raise ValueError(
raise VLLMValidationError(
"thinking_token_budget is set but reasoning_config is "
"not configured. Please set --reasoning-parser "
"and/or --reasoning-config to use thinking_token_budget."
)
if self.use_v2_model_runner:
raise ValueError(
raise VLLMValidationError(
"thinking_token_budget is not yet supported by the V2 "
"model runner. Run vLLM with VLLM_USE_V2_MODEL_RUNNER=0 "
"to use thinking_token_budget."
@@ -120,7 +121,7 @@ class InputProcessor:
task for task in supported_tasks if task in POOLING_TASKS
]
if not supported_pooling_tasks:
raise ValueError("This model does not support pooling")
raise VLLMValidationError("This model does not support pooling")
if params.task is None:
if "token_embed" in supported_pooling_tasks:
@@ -131,7 +132,7 @@ class InputProcessor:
params.task = "plugin"
if params.task not in supported_pooling_tasks:
raise ValueError(
raise VLLMValidationError(
f"Unsupported task: {params.task!r} "
f"Supported tasks: {supported_pooling_tasks}"
)
@@ -149,7 +150,7 @@ class InputProcessor:
# LoRA request passed in while LoRA is not enabled
if not self.lora_config:
raise ValueError(
raise VLLMValidationError(
f"Got lora_request {lora_request} but LoRA is not enabled!"
)
@@ -261,7 +262,7 @@ class InputProcessor:
dp_local_size = parallel_config.data_parallel_size_local
num_ranks = dp_local_size if parallel_config.local_engines_only else dp_size
if data_parallel_rank is not None and not (0 <= data_parallel_rank < num_ranks):
raise ValueError(
raise VLLMValidationError(
f"data_parallel_rank {data_parallel_rank} "
f"is out of range [0, {num_ranks})."
)
@@ -393,7 +394,7 @@ class InputProcessor:
return
if prompt_len == 0 and prompt_type == "decoder":
raise ValueError(f"The {prompt_type} prompt cannot be empty")
raise VLLMValidationError(f"The {prompt_type} prompt cannot be empty")
model_config = self.model_config
max_prompt_len = (
@@ -415,7 +416,7 @@ class InputProcessor:
"number of text tokens."
)
raise ValueError(
raise VLLMValidationError(
f"The {prompt_type} prompt (length {prompt_len}) is "
f"longer than the maximum model length of {max_prompt_len}. "
f"{suggestion}"
@@ -425,7 +426,7 @@ class InputProcessor:
"Make sure that `max_model_len` is no smaller than the "
"number of text tokens (prompt + requested output tokens)."
)
raise ValueError(
raise VLLMValidationError(
f"The {prompt_type} prompt (length {prompt_len}) plus the number of "
f"requested output tokens (at least 1) is longer than the maximum "
f"model length of {max_prompt_len}. {suggestion}"
@@ -457,7 +458,7 @@ class InputProcessor:
for mm_position in mm_positions:
num_embeds = mm_position.get_num_embeds()
if num_embeds > self.mm_encoder_cache_size:
raise ValueError(
raise VLLMValidationError(
f"The {prompt_type} prompt contains a(n) {modality} item "
f"with {num_embeds} embedding tokens, which exceeds the "
f"pre-allocated encoder cache size "
@@ -481,7 +482,9 @@ class InputProcessor:
# truly out-of-vocabulary.
model_vocab_size = model_config.get_vocab_size()
if max_input_id > max(tokenizer.max_token_id, model_vocab_size - 1):
raise ValueError(f"Token id {max_input_id} is out of vocabulary")
raise VLLMValidationError(
f"Token id {max_input_id} is out of vocabulary"
)
def _validate_model_inputs(
self,
+7 -1
View File
@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING
import torch
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.logits_process import LogitsProcessor as RequestLogitsProcessor
from vllm.sampling_params import SamplingParams
@@ -228,7 +229,12 @@ def validate_logits_processors_parameters(
tuple(logits_processors) if logits_processors is not None else None
)
for logits_procs in cached_load_custom_logitsprocs(logits_processors):
logits_procs.validate_params(sampling_params)
try:
logits_procs.validate_params(sampling_params)
except ValueError as e:
# Legacy custom logitsprocs may still raise ValueError from
# validate_params; convert for backward compatibility.
raise VLLMValidationError(str(e)) from e
class AdapterLogitsProcessor(LogitsProcessor):
+3 -1
View File
@@ -62,7 +62,9 @@ class LogitsProcessor(ABC):
def validate_params(cls, sampling_params: SamplingParams):
"""Validate sampling params for this logits processor.
Raise ValueError for invalid ones.
Raise ``VLLMValidationError`` (preferred) / ``ValueError`` (backward compatible)
for invalid params. Bare ``ValueError`` is converted to ``VLLMValidationError``
at the engine boundary so online serving returns HTTP 400.
"""
return None