[Chore] Bump Python version and apply formatting changes for v0.12 release (#126)

Signed-off-by: DarkLight1337 <tlleungac@connect.ust.hk>
This commit is contained in:
Cyrus Leung authored and GitHub committed 2025-12-16 15:19:40 +08:00
1 parent 31fedcfa2b
commit c091a03d82
61 files changed
+534 -553

No files matched your search

+14 -14
View File
@@ -6,7 +6,7 @@ import time
from argparse import Namespace
from collections.abc import AsyncGenerator, Iterable, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional, Union
from typing import Any
import torch
@@ -261,11 +261,11 @@ class AsyncOmni(EngineClient):
self,
prompt: PromptType,
request_id: str,
sampling_params_list: Optional[Union[SamplingParams, Sequence[SamplingParams]]] = None,
lora_request: Optional[LoRARequest] = None,
trace_headers: Optional[Mapping[str, str]] = None,
sampling_params_list: SamplingParams | Sequence[SamplingParams] | None = None,
lora_request: LoRARequest | None = None,
trace_headers: Mapping[str, str] | None = None,
priority: int = 0,
data_parallel_rank: Optional[int] = None,
data_parallel_rank: int | None = None,
) -> AsyncGenerator[OmniRequestOutput, None]:
"""Generate outputs for the given prompt asynchronously.
@@ -577,7 +577,7 @@ class AsyncOmni(EngineClient):
def dead_error(self) -> BaseException:
return EngineDeadError()
async def abort(self, request_id: Union[str, Iterable[str]]) -> None:
async def abort(self, request_id: str | Iterable[str]) -> None:
pass
async def get_vllm_config(self) -> VllmConfig:
@@ -620,13 +620,13 @@ class AsyncOmni(EngineClient):
async def reset_mm_cache(self) -> None:
pass
async def reset_prefix_cache(self, device: Optional[Device] = None) -> None:
async def reset_prefix_cache(self, device: Device | None = None) -> None:
pass
async def sleep(self, level: int = 1) -> None:
pass
async def wake_up(self, tags: Optional[list[str]] = None) -> None:
async def wake_up(self, tags: list[str] | None = None) -> None:
pass
async def is_sleeping(self) -> bool:
@@ -689,8 +689,8 @@ class AsyncOmniStageLLM(AsyncLLM):
use_cached_outputs: bool = False,
log_requests: bool = True,
start_engine_loop: bool = True,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
client_addresses: Optional[dict[str, str]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
) -> None:
@@ -771,7 +771,7 @@ class AsyncOmniStageLLM(AsyncLLM):
)
# Loggers.
self.logger_manager: Optional[StatLoggerManager] = None
self.logger_manager: StatLoggerManager | None = None
if self.log_stats:
self.logger_manager = StatLoggerManager(
vllm_config=vllm_config,
@@ -782,7 +782,7 @@ class AsyncOmniStageLLM(AsyncLLM):
)
self.logger_manager.log_engine_initialized()
self.output_handler: Optional[asyncio.Task] = None
self.output_handler: asyncio.Task | None = None
try:
# Start output handler eagerly if we are in the asyncio eventloop.
asyncio.get_running_loop()
@@ -819,10 +819,10 @@ class AsyncOmniStageLLM(AsyncLLM):
engine_args: AsyncOmniEngineArgs,
start_engine_loop: bool = True,
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
enable_log_requests: bool = False,
disable_log_stats: bool = False,
client_addresses: Optional[dict[str, str]] = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
disable_log_requests: bool = True, # Deprecated, will be removed
+11 -11
View File
@@ -1,5 +1,5 @@
from collections.abc import Awaitable, Iterable
from typing import Any, Optional, Union, cast
from typing import Any, cast
import numpy as np
from openai.types.chat import ChatCompletionContentPartTextParam
@@ -33,13 +33,13 @@ class OmniAsyncMultiModalItemTracker(AsyncMultiModalItemTracker):
class OmniAsyncMultiModalContentParser(AsyncMultiModalContentParser):
def __init__(self, tracker: AsyncMultiModalItemTracker) -> None:
super().__init__(tracker=tracker)
self._mm_processor_kwargs: Optional[dict[str, Any]] = None
self._mm_processor_kwargs: dict[str, Any] | None = None
def set_mm_processor_kwargs(self, mm_processor_kwargs: Optional[dict[str, Any]]) -> None:
def set_mm_processor_kwargs(self, mm_processor_kwargs: dict[str, Any] | None) -> None:
"""Set mm_processor_kwargs for use in parsing."""
self._mm_processor_kwargs = mm_processor_kwargs
def parse_video(self, video_url: Optional[str], uuid: Optional[str] = None) -> None:
def parse_video(self, video_url: str | None, uuid: str | None = None) -> None:
video = self._connector.fetch_video_async(video_url=video_url) if video_url else None
placeholder = self._tracker.add("video", video, uuid)
@@ -51,7 +51,7 @@ class OmniAsyncMultiModalContentParser(AsyncMultiModalContentParser):
audio_placeholder = self._tracker.add("audio", audio_coro, uuid)
self._add_placeholder("audio", audio_placeholder)
async def _extract_audio_from_video_async(self, video_url: str) -> tuple[np.ndarray, Union[int, float]]:
async def _extract_audio_from_video_async(self, video_url: str) -> tuple[np.ndarray, int | float]:
"""
Extract audio from video URL using librosa.
Returns tuple of (audio_array, sample_rate) compatible with audio format.
@@ -79,7 +79,7 @@ class OmniAsyncMultiModalContentParser(AsyncMultiModalContentParser):
temp_file.write(data)
return temp_file.name
def _load_audio_sync(file_path: str) -> tuple[np.ndarray, Union[int, float]]:
def _load_audio_sync(file_path: str) -> tuple[np.ndarray, int | float]:
"""Synchronous audio loading with librosa - runs in thread pool."""
import librosa
@@ -131,11 +131,11 @@ def parse_chat_messages_futures(
model_config: ModelConfig,
tokenizer: AnyTokenizer,
content_format: _ChatTemplateContentFormat,
mm_processor_kwargs: Optional[dict[str, Any]] = None,
mm_processor_kwargs: dict[str, Any] | None = None,
) -> tuple[
list[ConversationMessage],
Awaitable[Optional[MultiModalDataDict]],
Optional[MultiModalUUIDDict],
Awaitable[MultiModalDataDict | None],
MultiModalUUIDDict | None,
]:
conversation: list[ConversationMessage] = []
mm_tracker = OmniAsyncMultiModalItemTracker(model_config, tokenizer)
@@ -165,7 +165,7 @@ def _parse_chat_message_content(
mm_tracker: BaseMultiModalItemTracker,
content_format: _ChatTemplateContentFormat,
interleave_strings: bool,
mm_processor_kwargs: Optional[dict[str, Any]] = None,
mm_processor_kwargs: dict[str, Any] | None = None,
) -> list[ConversationMessage]:
role = message["role"]
content = message.get("content")
@@ -210,7 +210,7 @@ def _parse_chat_message_content_parts(
*,
wrap_dicts: bool,
interleave_strings: bool,
mm_processor_kwargs: Optional[dict[str, Any]] = None,
mm_processor_kwargs: dict[str, Any] | None = None,
) -> list[ConversationMessage]:
content = list[_ContentPart]()
+11 -11
View File
@@ -4,7 +4,7 @@ import time
import uuid
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional, Union
from typing import Any
import cloudpickle
from pydantic import ValidationError
@@ -89,9 +89,9 @@ class OmniLLM:
def __init__(
self,
model: str,
stage_configs_path: Optional[str] = None,
stage_configs_path: str | None = None,
log_stats: bool = False,
log_file: Optional[str] = None,
log_file: str | None = None,
init_sleep_seconds: int = 20,
shm_threshold_bytes: int = 65536,
batch_timeout: int = 10,
@@ -228,8 +228,8 @@ class OmniLLM:
def generate(
self,
prompts: Union[PromptType, Sequence[PromptType]],
sampling_params_list: Optional[Union[SamplingParams, Sequence[SamplingParams]]] = None,
prompts: PromptType | Sequence[PromptType],
sampling_params_list: SamplingParams | Sequence[SamplingParams] | None = None,
) -> list[OmniRequestOutput]:
"""Generate outputs for the given prompts.
@@ -262,8 +262,8 @@ class OmniLLM:
def _run_generation(
self,
prompts: Union[PromptType, Sequence[PromptType]],
sampling_params_list: Optional[Union[SamplingParams, Sequence[SamplingParams]]] = None,
prompts: PromptType | Sequence[PromptType],
sampling_params_list: SamplingParams | Sequence[SamplingParams] | None = None,
) -> list[OmniRequestOutput]:
logger.debug("[Orchestrator] generate() called")
if sampling_params_list is None:
@@ -559,9 +559,9 @@ class OmniStageLLM(LLM):
def __init__(
self,
model: str,
compilation_config: Optional[Union[int, dict[str, Any], CompilationConfig]] = None,
hf_overrides: Optional[dict[str, Any]] = None,
structured_outputs_config: Optional[Union[dict[str, Any], StructuredOutputsConfig]] = None,
compilation_config: int | dict[str, Any] | CompilationConfig | None = None,
hf_overrides: dict[str, Any] | None = None,
structured_outputs_config: dict[str, Any] | StructuredOutputsConfig | None = None,
**kwargs: Any,
):
"""LLM constructor."""
@@ -633,7 +633,7 @@ class OmniStageLLM(LLM):
self.engine_class = type(self.llm_engine)
self.request_counter = Counter()
self.default_sampling_params: Union[dict[str, Any], None] = None
self.default_sampling_params: dict[str, Any] | None = None
supported_tasks = self.llm_engine.get_supported_tasks() # type: ignore
+12 -12
View File
@@ -16,7 +16,7 @@ import logging
import multiprocessing as mp
import os
import sys
from typing import Any, Optional, Union
from typing import Any
from vllm.inputs import TextPrompt
from vllm.inputs.preprocess import InputPreprocessor
@@ -81,10 +81,10 @@ class OmniStage:
default_sampling_params = getattr(stage_config, "default_sampling_params", {})
self.default_sampling_params = SamplingParams(**_to_dict(default_sampling_params))
# Runtime orchestration state (added)
self._in_q: Optional[mp.Queue] = None
self._out_q: Optional[mp.Queue] = None
self._proc: Optional[mp.Process] = None
self._log_file: Optional[str] = None
self._in_q: mp.Queue | None = None
self._out_q: mp.Queue | None = None
self._proc: mp.Process | None = None
self._log_file: str | None = None
self._shm_threshold_bytes: int = 65536
self._logger = logging.getLogger(__name__)
@@ -160,11 +160,11 @@ class OmniStage:
model: str,
*,
is_async: bool = False,
log_file: Optional[str] = None,
log_file: str | None = None,
shm_threshold_bytes: int = 65536,
ctx: Optional[mp.context.BaseContext] = None,
ctx: mp.context.BaseContext | None = None,
batch_timeout: int = 10,
connectors_config: Optional[dict] = None,
connectors_config: dict | None = None,
worker_backend: str = "multi_process",
**kwargs: Any,
) -> None:
@@ -303,7 +303,7 @@ class OmniStage:
assert self._in_q is not None
self._in_q.put(payload)
def try_collect(self) -> Optional[dict[str, Any]]:
def try_collect(self) -> dict[str, Any] | None:
"""Try to collect a result from the stage worker without blocking.
Returns:
@@ -317,8 +317,8 @@ class OmniStage:
return None
def process_engine_inputs(
self, stage_list: list[Any], prompt: Union[OmniTokensPrompt, TextPrompt] = None
) -> list[Union[OmniTokensPrompt, TextPrompt]]:
self, stage_list: list[Any], prompt: OmniTokensPrompt | TextPrompt = None
) -> list[OmniTokensPrompt | TextPrompt]:
"""Process engine inputs for this stage from upstream stage outputs.
Derives inputs for this stage from outputs of upstream stages.
@@ -372,7 +372,7 @@ def _stage_worker(
stage_payload: dict[str, Any],
in_q: mp.Queue,
out_q: mp.Queue,
log_file: Optional[str] = None,
log_file: str | None = None,
batch_timeout: int = 10,
) -> None:
"""Stage worker entry: device setup, LLM init, batching, SHM IPC."""
+7 -7
View File
@@ -5,7 +5,7 @@ from argparse import Namespace
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from http import HTTPStatus
from typing import Any, Optional
from typing import Any
import vllm.envs as envs
from fastapi import Depends, HTTPException, Request
@@ -111,8 +111,8 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
async def build_async_omni(
args: Namespace,
*,
disable_frontend_multiprocessing: Optional[bool] = None,
client_config: Optional[dict[str, Any]] = None,
disable_frontend_multiprocessing: bool | None = None,
client_config: dict[str, Any] | None = None,
) -> AsyncIterator[EngineClient]:
"""Build an AsyncOmni instance from command-line arguments.
@@ -152,7 +152,7 @@ async def build_async_omni_from_stage_config(
args: Namespace,
*,
disable_frontend_multiprocessing: bool = False,
client_config: Optional[dict[str, Any]] = None,
client_config: dict[str, Any] | None = None,
) -> AsyncIterator[EngineClient]:
"""Create AsyncOmni from stage configuration.
@@ -182,7 +182,7 @@ async def build_async_omni_from_stage_config(
"To disable frontend multiprocessing, set VLLM_USE_V1=0."
)
async_omni: Optional[EngineClient] = None
async_omni: EngineClient | None = None
try:
async_omni = AsyncOmni(model=args.model, cli_args=args)
@@ -257,7 +257,7 @@ async def omni_init_app_state(
)
if args.tool_server == "demo":
tool_server: Optional[ToolServer] = DemoToolServer()
tool_server: ToolServer | None = DemoToolServer()
assert isinstance(tool_server, DemoToolServer)
await tool_server.init_and_validate()
elif args.tool_server:
@@ -314,7 +314,7 @@ async def omni_init_app_state(
state.server_load_metrics = 0
def Omnichat(request: Request) -> Optional[OmniOpenAIServingChat]:
def Omnichat(request: Request) -> OmniOpenAIServingChat | None:
return request.app.state.openai_serving_chat
+17 -17
View File
@@ -3,10 +3,10 @@ import base64
import json
import time
import uuid
from collections.abc import AsyncGenerator, AsyncIterator, Sequence
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Sequence
from datetime import datetime, timedelta, timezone
from io import BytesIO
from typing import Any, Callable, Optional, Union
from typing import Any
import jinja2
from fastapi import Request
@@ -78,8 +78,8 @@ class OmniOpenAIServingChat(OpenAIServingChat):
async def create_chat_completion(
self,
request: ChatCompletionRequest,
raw_request: Optional[Request] = None,
) -> Union[AsyncGenerator[str, None], ChatCompletionResponse, ErrorResponse]:
raw_request: Request | None = None,
) -> AsyncGenerator[str, None] | ChatCompletionResponse | ErrorResponse:
"""
Chat Completion API similar to OpenAI's API.
@@ -236,17 +236,17 @@ class OmniOpenAIServingChat(OpenAIServingChat):
async def _preprocess_chat(
self,
request: Union[ChatLikeRequest, ResponsesRequest],
request: ChatLikeRequest | ResponsesRequest,
tokenizer: AnyTokenizer,
messages: list[ChatCompletionMessageParam],
chat_template: Optional[str],
chat_template: str | None,
chat_template_content_format: ChatTemplateContentFormatOption,
add_generation_prompt: bool = True,
continue_final_message: bool = False,
tool_dicts: Optional[list[dict[str, Any]]] = None,
documents: Optional[list[dict[str, str]]] = None,
chat_template_kwargs: Optional[dict[str, Any]] = None,
tool_parser: Optional[Callable[[AnyTokenizer], ToolParser]] = None,
tool_dicts: list[dict[str, Any]] | None = None,
documents: list[dict[str, str]] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
tool_parser: Callable[[AnyTokenizer], ToolParser] | None = None,
add_special_tokens: bool = False,
) -> tuple[
list[ConversationMessage],
@@ -279,7 +279,7 @@ class OmniOpenAIServingChat(OpenAIServingChat):
)
_chat_template_kwargs.update(chat_template_kwargs or {})
request_prompt: Union[str, list[int]]
request_prompt: str | list[int]
if tokenizer is None:
request_prompt = "placeholder"
@@ -365,9 +365,9 @@ class OmniOpenAIServingChat(OpenAIServingChat):
def _log_inputs(
self,
request_id: str,
inputs: Union[RequestPrompt, PromptType],
params_list: Optional[list[SamplingParams]],
lora_request: Optional[LoRARequest],
inputs: RequestPrompt | PromptType,
params_list: list[SamplingParams] | None,
lora_request: LoRARequest | None,
) -> None:
if self.request_logger is None:
return
@@ -399,9 +399,9 @@ class OmniOpenAIServingChat(OpenAIServingChat):
conversation: list[ConversationMessage],
tokenizer: AnyTokenizer,
request_metadata: RequestResponseMetadata,
) -> Union[ErrorResponse, ChatCompletionResponse]:
) -> ErrorResponse | ChatCompletionResponse:
created_time = int(time.time())
final_res: Optional[RequestOutput] = None
final_res: RequestOutput | None = None
final_outputs: list[OmniRequestOutput] = []
try:
@@ -698,7 +698,7 @@ class OmniOpenAIServingChat(OpenAIServingChat):
choices.append(choice_data)
if request.echo:
last_msg_content: Union[str, list[dict[str, str]]] = ""
last_msg_content: str | list[dict[str, str]] = ""
if conversation and "content" in conversation[-1] and conversation[-1].get("role") == role:
last_msg_content = conversation[-1]["content"] or ""
if isinstance(last_msg_content, list):
+3 -3
View File
@@ -2,7 +2,7 @@ import os
from collections import Counter
from dataclasses import asdict, is_dataclass
from pathlib import Path
from typing import Any, Optional
from typing import Any
from omegaconf import OmegaConf
from vllm.transformers_utils.config import get_config
@@ -97,7 +97,7 @@ def resolve_model_config_path(model: str) -> str:
return str(stage_config_path)
def load_stage_configs_from_model(model: str, base_engine_args: Optional[dict] = None) -> list:
def load_stage_configs_from_model(model: str, base_engine_args: dict | None = None) -> list:
"""Load stage configurations from model's default config file.
Loads stage configurations based on the model type and device type.
@@ -120,7 +120,7 @@ def load_stage_configs_from_model(model: str, base_engine_args: Optional[dict] =
return stage_configs
def load_stage_configs_from_yaml(config_path: str, base_engine_args: Optional[dict] = None) -> list:
def load_stage_configs_from_yaml(config_path: str, base_engine_args: dict | None = None) -> list:
"""Load stage configurations from a YAML file.
Args: