Bound generation inputs before expensive work (#51447)
Signed-off-by: Clinton Thomas <1033162+KernelClint@users.noreply.github.com> Co-authored-by: Lucas Bourtoule <35483370+dhalf@users.noreply.github.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Lucas Bourtoule
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent
5b184f775a
commit
b64a2708b0
@@ -30,6 +30,7 @@ from vllm.entrypoints.openai.engine.protocol import (
|
||||
FunctionDefinition,
|
||||
OpenAIBaseModel,
|
||||
PerRequestTimingMetrics,
|
||||
StopParam,
|
||||
StreamOptions,
|
||||
ToolCall,
|
||||
UsageInfo,
|
||||
@@ -228,7 +229,7 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
presence_penalty: float | None = 0.0
|
||||
response_format: AnyResponseFormat | None = None
|
||||
seed: int | None = Field(None, ge=_INT64_MIN, le=_INT64_MAX)
|
||||
stop: str | list[str] | None = []
|
||||
stop: StopParam = []
|
||||
stream: bool | None = False
|
||||
stream_options: StreamOptions | None = None
|
||||
temperature: float | None = None
|
||||
@@ -1077,7 +1078,7 @@ class BatchChatCompletionRequest(OpenAIBaseModel):
|
||||
presence_penalty: float | None = 0.0
|
||||
response_format: Any | None = None
|
||||
seed: int | None = Field(None, ge=_INT64_MIN, le=_INT64_MAX)
|
||||
stop: str | list[str] | None = Field(default_factory=list)
|
||||
stop: StopParam = Field(default_factory=list)
|
||||
temperature: float | None = None
|
||||
top_p: float | None = None
|
||||
user: str | None = None
|
||||
|
||||
@@ -14,6 +14,7 @@ from vllm.entrypoints.openai.engine.protocol import (
|
||||
AnyResponseFormat,
|
||||
OpenAIBaseModel,
|
||||
PerRequestTimingMetrics,
|
||||
StopParam,
|
||||
StreamOptions,
|
||||
UsageInfo,
|
||||
structured_outputs_from_response_format,
|
||||
@@ -61,7 +62,7 @@ class CompletionRequest(OpenAIBaseModel):
|
||||
n: int = 1
|
||||
presence_penalty: float | None = 0.0
|
||||
seed: int | None = Field(None, ge=_INT64_MIN, le=_INT64_MAX)
|
||||
stop: str | list[str] | None = []
|
||||
stop: StopParam = []
|
||||
stream: bool | None = False
|
||||
stream_options: StreamOptions | None = None
|
||||
suffix: str | None = None
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import json
|
||||
import time
|
||||
from http import HTTPStatus
|
||||
from typing import Any, ClassVar, Literal, TypeAlias
|
||||
from typing import Annotated, Any, ClassVar, Literal, TypeAlias
|
||||
|
||||
import regex as re
|
||||
from pydantic import (
|
||||
@@ -17,6 +17,7 @@ from pydantic import (
|
||||
model_validator,
|
||||
)
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config.utils import replace
|
||||
from vllm.entrypoints.chat_utils import make_tool_call_id
|
||||
from vllm.exceptions import VLLMServerError, VLLMValidationError
|
||||
@@ -27,6 +28,10 @@ from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
StopParam: TypeAlias = (
|
||||
str | Annotated[list[str], Field(max_length=envs.VLLM_MAX_STOP_STRINGS)] | None
|
||||
)
|
||||
|
||||
|
||||
class OpenAIBaseModel(BaseModel):
|
||||
# OpenAI API does allow extra fields
|
||||
|
||||
@@ -60,7 +60,7 @@ from vllm.entrypoints.chat_utils import (
|
||||
ChatCompletionMessageParam,
|
||||
ChatTemplateContentFormatOption,
|
||||
)
|
||||
from vllm.entrypoints.openai.engine.protocol import OpenAIBaseModel
|
||||
from vllm.entrypoints.openai.engine.protocol import OpenAIBaseModel, StopParam
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.renderers import ChatParams, TokenizeParams, merge_kwargs
|
||||
@@ -281,7 +281,7 @@ class ResponsesRequest(OpenAIBaseModel):
|
||||
|
||||
repetition_penalty: float | None = None
|
||||
seed: int | None = Field(None, ge=_INT64_MIN, le=_INT64_MAX)
|
||||
stop: str | list[str] | None = []
|
||||
stop: StopParam = []
|
||||
ignore_eos: bool = False
|
||||
vllm_xargs: dict[str, str | int | float | list[str | int | float]] | None = Field(
|
||||
default=None,
|
||||
|
||||
@@ -108,6 +108,9 @@ if TYPE_CHECKING:
|
||||
VLLM_HTTP_TIMEOUT_KEEP_ALIVE: int = 5 # seconds
|
||||
VLLM_MAX_N_SEQUENCES: int = 16384
|
||||
VLLM_MAX_COMPLETION_PROMPTS: int = 1024
|
||||
VLLM_MAX_STOP_STRINGS: int = 4
|
||||
VLLM_MAX_NUM_BAD_WORDS: int = 128
|
||||
VLLM_MAX_BAD_WORDS_TOTAL_TOKENS: int = 1024
|
||||
VLLM_PLUGINS: list[str] | None = None
|
||||
VLLM_LORA_RESOLVER_CACHE_DIR: str | None = None
|
||||
VLLM_LORA_RESOLVER_HF_REPO_LIST: str | None = None
|
||||
@@ -1114,6 +1117,17 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_MAX_COMPLETION_PROMPTS": lambda: int(
|
||||
os.environ.get("VLLM_MAX_COMPLETION_PROMPTS", "1024")
|
||||
),
|
||||
# Maximum number of stop strings allowed in a single request.
|
||||
"VLLM_MAX_STOP_STRINGS": lambda: int(os.environ.get("VLLM_MAX_STOP_STRINGS", "4")),
|
||||
# Maximum number of bad-word token sequences generated per request.
|
||||
"VLLM_MAX_NUM_BAD_WORDS": lambda: int(
|
||||
os.environ.get("VLLM_MAX_NUM_BAD_WORDS", "128")
|
||||
),
|
||||
# Maximum total number of bad-word tokens (summed across all bad words)
|
||||
# allowed per request. Bounds the per-request GPU buffer width.
|
||||
"VLLM_MAX_BAD_WORDS_TOTAL_TOKENS": lambda: int(
|
||||
os.environ.get("VLLM_MAX_BAD_WORDS_TOTAL_TOKENS", "1024")
|
||||
),
|
||||
# a list of plugin names to load, separated by commas.
|
||||
# if this is not set, it means all plugins will be loaded
|
||||
# if this is set to an empty string, no plugins will be loaded
|
||||
|
||||
+33
-13
@@ -32,6 +32,22 @@ MAX_LOGPROB_TOKEN_IDS = 128
|
||||
the per-request row width allocated by the sampler's `LogprobTokenIdsState`."""
|
||||
|
||||
|
||||
def _verify_num_sequences(value: int, parameter_name: str) -> None:
|
||||
if not isinstance(value, int):
|
||||
raise VLLMValidationError(
|
||||
f"{parameter_name} must be an int, but is of type {type(value)}"
|
||||
)
|
||||
if value < 1:
|
||||
raise VLLMValidationError(f"{parameter_name} must be at least 1, got {value}.")
|
||||
max_n = envs.VLLM_MAX_N_SEQUENCES
|
||||
if value > max_n:
|
||||
raise VLLMValidationError(
|
||||
f"{parameter_name} must be at most {max_n}, got {value}. "
|
||||
"To increase this limit, set the VLLM_MAX_N_SEQUENCES "
|
||||
"environment variable."
|
||||
)
|
||||
|
||||
|
||||
def validate_thinking_token_budget(value: int | float | bool | None) -> int | None:
|
||||
"""Validate ``thinking_token_budget``; return ``None`` if unset."""
|
||||
if value is None:
|
||||
@@ -479,9 +495,13 @@ class SamplingParams(
|
||||
|
||||
if self.stop_token_ids is None:
|
||||
self.stop_token_ids = []
|
||||
else:
|
||||
self.stop_token_ids = list(dict.fromkeys(self.stop_token_ids))
|
||||
|
||||
if self.bad_words is None:
|
||||
self.bad_words = []
|
||||
else:
|
||||
self.bad_words = list(dict.fromkeys(self.bad_words))
|
||||
|
||||
if self.logprobs is True:
|
||||
self.logprobs = 1
|
||||
@@ -513,19 +533,7 @@ class SamplingParams(
|
||||
self.skip_reading_prefix_cache = self.prompt_logprobs is not None
|
||||
|
||||
def _verify_args(self) -> None:
|
||||
if not isinstance(self.n, int):
|
||||
raise VLLMValidationError(
|
||||
f"n must be an int, but is of type {type(self.n)}"
|
||||
)
|
||||
if self.n < 1:
|
||||
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 VLLMValidationError(
|
||||
f"n must be at most {max_n}, got {self.n}. "
|
||||
"To increase this limit, set the VLLM_MAX_N_SEQUENCES "
|
||||
"environment variable."
|
||||
)
|
||||
_verify_num_sequences(self.n, "n")
|
||||
if not -2.0 <= self.presence_penalty <= 2.0:
|
||||
raise VLLMValidationError(
|
||||
f"presence_penalty must be in [-2, 2], got {self.presence_penalty}."
|
||||
@@ -677,6 +685,7 @@ class SamplingParams(
|
||||
if not self.bad_words:
|
||||
return
|
||||
self._bad_words_token_ids = []
|
||||
max_num_bad_words = envs.VLLM_MAX_NUM_BAD_WORDS
|
||||
for bad_word in self.bad_words:
|
||||
# To prohibit words both at the beginning
|
||||
# and in the middle of text
|
||||
@@ -696,6 +705,14 @@ class SamplingParams(
|
||||
and len(prompt_token_ids) == len(self._bad_words_token_ids[-1])
|
||||
):
|
||||
self._bad_words_token_ids.append(prompt_token_ids)
|
||||
if len(self._bad_words_token_ids) > max_num_bad_words:
|
||||
raise VLLMValidationError(
|
||||
f"Too many bad words after tokenization: "
|
||||
f"{len(self._bad_words_token_ids)}. "
|
||||
f"The max number is {max_num_bad_words}.",
|
||||
parameter="bad_words",
|
||||
value=self.bad_words,
|
||||
)
|
||||
|
||||
invalid_token_ids = [
|
||||
token_id
|
||||
@@ -1147,3 +1164,6 @@ class BeamSearchParams(
|
||||
length_penalty: float = 1.0
|
||||
include_stop_str_in_output: bool = False
|
||||
structured_outputs: StructuredOutputsParams | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_verify_num_sequences(self.beam_width, "beam_width")
|
||||
|
||||
@@ -119,7 +119,10 @@ def find_last_user_index(messages: list[dict[str, Any]]) -> int:
|
||||
|
||||
|
||||
def render_message(
|
||||
index: int, messages: list[dict[str, Any]], thinking_mode: str
|
||||
index: int,
|
||||
messages: list[dict[str, Any]],
|
||||
thinking_mode: str,
|
||||
last_user_idx: int | None = None,
|
||||
) -> str:
|
||||
if not (0 <= index < len(messages)):
|
||||
raise ValueError(
|
||||
@@ -130,7 +133,9 @@ def render_message(
|
||||
|
||||
prompt = ""
|
||||
msg = messages[index]
|
||||
last_user_idx = find_last_user_index(messages)
|
||||
last_user_idx = (
|
||||
find_last_user_index(messages) if last_user_idx is None else last_user_idx
|
||||
)
|
||||
|
||||
role = msg.get("role")
|
||||
content = msg.get("content")
|
||||
@@ -294,9 +299,14 @@ def encode_messages(
|
||||
if thinking_mode == "thinking" and drop_thinking:
|
||||
full_messages = drop_thinking_messages(full_messages)
|
||||
|
||||
last_user_idx = find_last_user_index(full_messages)
|
||||
|
||||
for idx in range(len(messages)):
|
||||
prompt += render_message(
|
||||
idx + len(context), full_messages, thinking_mode=thinking_mode
|
||||
idx + len(context),
|
||||
full_messages,
|
||||
thinking_mode=thinking_mode,
|
||||
last_user_idx=last_user_idx,
|
||||
)
|
||||
|
||||
return prompt
|
||||
|
||||
@@ -199,7 +199,14 @@ def find_last_user_index(messages: List[Dict[str, Any]]) -> int:
|
||||
# Message Rendering
|
||||
# ============================================================
|
||||
|
||||
def render_message(index: int, messages: List[Dict[str, Any]], thinking_mode: str, drop_thinking: bool = True, reasoning_effort: Optional[str] = None) -> str:
|
||||
def render_message(
|
||||
index: int,
|
||||
messages: List[Dict[str, Any]],
|
||||
thinking_mode: str,
|
||||
drop_thinking: bool = True,
|
||||
reasoning_effort: Optional[str] = None,
|
||||
last_user_idx: Optional[int] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Render a single message at the given index into its encoded string form.
|
||||
|
||||
@@ -213,6 +220,7 @@ def render_message(index: int, messages: List[Dict[str, Any]], thinking_mode: st
|
||||
drop_thinking: Whether to drop reasoning content from earlier turns.
|
||||
reasoning_effort: Reasoning effort level, one of "low", "high", "max".
|
||||
None is treated as "low".
|
||||
last_user_idx: Cached index of the last user/developer message.
|
||||
|
||||
Returns:
|
||||
Encoded string for this message.
|
||||
@@ -222,7 +230,9 @@ def render_message(index: int, messages: List[Dict[str, Any]], thinking_mode: st
|
||||
|
||||
prompt = ""
|
||||
msg = messages[index]
|
||||
last_user_idx = find_last_user_index(messages)
|
||||
last_user_idx = (
|
||||
find_last_user_index(messages) if last_user_idx is None else last_user_idx
|
||||
)
|
||||
|
||||
role = msg.get("role")
|
||||
content = msg.get("content")
|
||||
@@ -544,6 +554,8 @@ def encode_messages(
|
||||
num_to_render = len(messages)
|
||||
context_len = len(context)
|
||||
|
||||
last_user_idx = find_last_user_index(full_messages)
|
||||
|
||||
for idx in range(num_to_render):
|
||||
prompt += render_message(
|
||||
idx + context_len,
|
||||
@@ -551,6 +563,7 @@ def encode_messages(
|
||||
thinking_mode=thinking_mode,
|
||||
drop_thinking=effective_drop_thinking,
|
||||
reasoning_effort=reasoning_effort,
|
||||
last_user_idx=last_user_idx,
|
||||
)
|
||||
|
||||
return prompt
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.worker.gpu.buffer_utils import StagedWriteTensor, UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
MAX_BAD_WORDS_TOTAL_TOKENS = 1024 # Max total tokens for all bad words per request
|
||||
MAX_NUM_BAD_WORDS = 128 # Max number of bad words per request
|
||||
|
||||
|
||||
class BadWordsState:
|
||||
def __init__(self, req_states: RequestState):
|
||||
@@ -18,15 +16,17 @@ class BadWordsState:
|
||||
self.max_num_reqs = req_states.max_num_reqs
|
||||
self.device = req_states.device
|
||||
|
||||
# flattened bad word tokens: [max_num_reqs, MAX_BAD_WORDS_TOTAL_TOKENS]
|
||||
max_total_tokens = envs.VLLM_MAX_BAD_WORDS_TOTAL_TOKENS
|
||||
max_num_bad_words = envs.VLLM_MAX_NUM_BAD_WORDS
|
||||
# flattened bad word tokens: [max_num_reqs, VLLM_MAX_BAD_WORDS_TOTAL_TOKENS]
|
||||
self.bad_word_token_ids = StagedWriteTensor(
|
||||
(self.max_num_reqs, MAX_BAD_WORDS_TOTAL_TOKENS),
|
||||
(self.max_num_reqs, max_total_tokens),
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
# cumulative offsets of bad words: [max_num_reqs, MAX_NUM_BAD_WORDS + 1]
|
||||
# cumulative offsets of bad words: [max_num_reqs, VLLM_MAX_NUM_BAD_WORDS + 1]
|
||||
self.bad_word_offsets = StagedWriteTensor(
|
||||
(self.max_num_reqs, MAX_NUM_BAD_WORDS + 1),
|
||||
(self.max_num_reqs, max_num_bad_words + 1),
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
@@ -40,10 +40,11 @@ class BadWordsState:
|
||||
return
|
||||
|
||||
num_bad_words = len(bad_words_token_ids)
|
||||
if num_bad_words > MAX_NUM_BAD_WORDS:
|
||||
max_num_bad_words = envs.VLLM_MAX_NUM_BAD_WORDS
|
||||
if num_bad_words > max_num_bad_words:
|
||||
raise ValueError(
|
||||
f"Too many bad words: {num_bad_words}. "
|
||||
f"The max number is {MAX_NUM_BAD_WORDS}."
|
||||
f"The max number is {max_num_bad_words}."
|
||||
)
|
||||
|
||||
# Flatten bad words and compute offsets
|
||||
@@ -53,10 +54,11 @@ class BadWordsState:
|
||||
flattened_tokens.extend(bad_word)
|
||||
offsets.append(len(flattened_tokens))
|
||||
|
||||
if len(flattened_tokens) > MAX_BAD_WORDS_TOTAL_TOKENS:
|
||||
max_total_tokens = envs.VLLM_MAX_BAD_WORDS_TOTAL_TOKENS
|
||||
if len(flattened_tokens) > max_total_tokens:
|
||||
raise ValueError(
|
||||
f"Too many total bad word tokens: {len(flattened_tokens)}. "
|
||||
f"The max is {MAX_BAD_WORDS_TOTAL_TOKENS}."
|
||||
f"The max is {max_total_tokens}."
|
||||
)
|
||||
|
||||
# Stage writes
|
||||
|
||||
Reference in New Issue
Block a user