[Entrypoint][Refactor] vLLM-Omni Entrypoint Refactoring (#1908)
Signed-off-by: yinpe <11810305@mail.sustech.edu.cn> Signed-off-by: Peiqi Yin <yinpeiqi809@gmail.com> Signed-off-by: yinpeiqi <yinpeiqi809@gmail.com> Signed-off-by: wuhang <whlbx@hotmail.com> Signed-off-by: linyueqian <linyueqian@outlook.com> Signed-off-by: princepride <wangzhipeng628@gmail.com> Signed-off-by: lishunyang <lishunyang12@163.com> Signed-off-by: Chenguang ZHENG <645327136@qq.com> Signed-off-by: Peiqi Yin <60515999+yinpeiqi@users.noreply.github.com> Co-authored-by: yinpe <11810305@mail.sustech.edu.cn> Co-authored-by: Peiqi Yin <yinpeiqi809@gmail.com> Co-authored-by: wuhang <whlbx@hotmail.com> Co-authored-by: Peiqi Yin <60515999+yinpeiqi@users.noreply.github.com> Co-authored-by: linyueqian <linyueqian@outlook.com> Co-authored-by: princepride <wangzhipeng628@gmail.com> Co-authored-by: lishunyang <lishunyang12@163.com>
This commit is contained in:
125 files changed
+5210
-9322
No files matched your search
@@ -3,11 +3,6 @@
|
||||
|
||||
"""
|
||||
vLLM-Omni entrypoints module.
|
||||
|
||||
Provides high-level interfaces for running omni models including:
|
||||
- AsyncOmni: Async orchestrator for multi-stage LLM pipelines
|
||||
- AsyncOmniDiffusion: Async interface for diffusion model inference
|
||||
- Omni: Unified entrypoint that auto-selects between LLM and Diffusion
|
||||
"""
|
||||
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
|
||||
+472
-999
File diff suppressed because it is too large.
Load diff
@@ -10,6 +10,7 @@ enabling concurrent request handling and streaming generation.
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
import weakref
|
||||
from collections.abc import AsyncGenerator, Iterable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any
|
||||
@@ -27,6 +28,18 @@ from vllm_omni.outputs import OmniRequestOutput
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _weak_close_async_omni_diffusion(engine: DiffusionEngine, executor: ThreadPoolExecutor) -> None:
|
||||
"""Best-effort diffusion cleanup for GC finalization."""
|
||||
try:
|
||||
engine.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
executor.shutdown(wait=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class AsyncOmniDiffusion:
|
||||
"""Async entry point for vLLM-Omni diffusion model inference.
|
||||
|
||||
@@ -127,6 +140,12 @@ class AsyncOmniDiffusion:
|
||||
# Thread pool for running sync engine in async context
|
||||
self._executor = ThreadPoolExecutor(max_workers=1)
|
||||
self._closed = False
|
||||
self._weak_finalizer = weakref.finalize(
|
||||
self,
|
||||
_weak_close_async_omni_diffusion,
|
||||
self.engine,
|
||||
self._executor,
|
||||
)
|
||||
|
||||
logger.info("AsyncOmniDiffusion initialized with model: %s", model)
|
||||
|
||||
@@ -217,6 +236,9 @@ class AsyncOmniDiffusion:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
finalizer = getattr(self, "_weak_finalizer", None)
|
||||
if finalizer is not None and finalizer.alive:
|
||||
finalizer.detach()
|
||||
|
||||
try:
|
||||
self.engine.close()
|
||||
@@ -234,13 +256,6 @@ class AsyncOmniDiffusion:
|
||||
"""Alias for close() method."""
|
||||
self.close()
|
||||
|
||||
def __del__(self) -> None:
|
||||
"""Best-effort cleanup on deletion."""
|
||||
try:
|
||||
self.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def abort(self, request_id: str | Iterable[str]) -> None:
|
||||
"""Abort a request."""
|
||||
self.engine.abort(request_id)
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import os
|
||||
import socket
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
|
||||
from vllm.renderers import renderer_from_config
|
||||
from vllm.tracing import init_tracer
|
||||
from vllm.transformers_utils.config import maybe_register_config_serialize_by_value
|
||||
from vllm.usage.usage_lib import UsageContext
|
||||
from vllm.utils.func_utils import deprecate_kwargs
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.engine.core_client import EngineCoreClient
|
||||
from vllm.v1.executor.abstract import Executor
|
||||
from vllm.v1.metrics.loggers import StatLoggerFactory, StatLoggerManager
|
||||
|
||||
from vllm_omni.engine.arg_utils import AsyncOmniEngineArgs
|
||||
from vllm_omni.engine.input_processor import OmniInputProcessor
|
||||
from vllm_omni.engine.output_processor import MultimodalOutputProcessor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class AsyncOmniLLM(AsyncLLM):
|
||||
"""Async single-stage LLM engine for use within a stage worker process.
|
||||
|
||||
This class extends the base vLLM AsyncLLM class with omni-specific
|
||||
processors for handling multimodal inputs and outputs. It is used
|
||||
internally by AsyncOmniStage workers and should not be instantiated
|
||||
directly by users.
|
||||
|
||||
Args:
|
||||
engine_args: AsyncOmniEngineArgs containing engine configuration
|
||||
vllm_config: Global vLLM configuration
|
||||
executor_class: Executor implementation class, e.g. MultiprocExecutor
|
||||
log_stats: Whether to log statistics
|
||||
usage_context: Usage context of the LLM (default: ENGINE_CONTEXT)
|
||||
mm_registry: Multi-modal registry for processing multimodal inputs
|
||||
use_cached_outputs: Whether to use cached outputs
|
||||
log_requests: Whether to log requests
|
||||
start_engine_loop: Whether to start the engine loop automatically
|
||||
stat_loggers: Customized stat loggers for the engine.
|
||||
If not provided, default stat loggers will be used.
|
||||
Note: Stat logger interface may change in V1.
|
||||
client_addresses: Optional dictionary mapping client names to addresses
|
||||
client_count: Total number of clients (default: 1)
|
||||
client_index: Index of this client (default: 0)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine_args: AsyncOmniEngineArgs,
|
||||
vllm_config: VllmConfig,
|
||||
executor_class: type[Executor],
|
||||
log_stats: bool,
|
||||
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
|
||||
mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
|
||||
use_cached_outputs: bool = False,
|
||||
log_requests: bool = True,
|
||||
start_engine_loop: bool = True,
|
||||
stat_loggers: list[StatLoggerFactory] | None = None,
|
||||
client_addresses: dict[str, str] | None = None,
|
||||
client_count: int = 1,
|
||||
client_index: int = 0,
|
||||
) -> None:
|
||||
"""
|
||||
Create an AsyncOmniLLM.
|
||||
|
||||
Args:
|
||||
vllm_config: global configuration.
|
||||
executor_class: an Executor impl, e.g. MultiprocExecutor.
|
||||
log_stats: Whether to log stats.
|
||||
usage_context: Usage context of the LLM.
|
||||
mm_registry: Multi-modal registry.
|
||||
use_cached_outputs: Whether to use cached outputs.
|
||||
log_requests: Whether to log requests.
|
||||
start_engine_loop: Whether to start the engine loop.
|
||||
stat_loggers: customized stat loggers for the engine.
|
||||
If not provided, default stat loggers will be used.
|
||||
PLEASE BE AWARE THAT STAT LOGGER IS NOT STABLE
|
||||
IN V1, AND ITS BASE CLASS INTERFACE MIGHT CHANGE.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
# Ensure we can serialize custom transformer configs
|
||||
maybe_register_config_serialize_by_value()
|
||||
|
||||
self.model_config = vllm_config.model_config
|
||||
self.vllm_config = vllm_config
|
||||
self.observability_config = vllm_config.observability_config
|
||||
self.log_requests = log_requests
|
||||
|
||||
self.log_stats = log_stats or (stat_loggers is not None)
|
||||
if not log_stats and stat_loggers is not None:
|
||||
logger.info(
|
||||
"AsyncLLM created with log_stats=False and non-empty custom logger list; "
|
||||
"enabling logging without default stat loggers"
|
||||
)
|
||||
|
||||
# InputProcessor (converts Inputs --> EngineCoreRequests).
|
||||
self.input_processor = OmniInputProcessor(
|
||||
vllm_config=vllm_config,
|
||||
mm_registry=mm_registry,
|
||||
)
|
||||
|
||||
self.renderer = renderer_from_config(self.vllm_config)
|
||||
|
||||
# OutputProcessor (converts EngineCoreOutputs --> RequestOutput).
|
||||
self.output_processor = MultimodalOutputProcessor(
|
||||
tokenizer=self.renderer.tokenizer,
|
||||
log_stats=self.log_stats,
|
||||
engine_core_output_type=engine_args.engine_output_type,
|
||||
)
|
||||
|
||||
if self.observability_config.otlp_traces_endpoint is not None:
|
||||
tracer = init_tracer("vllm.llm_engine", self.observability_config.otlp_traces_endpoint)
|
||||
self.output_processor.tracer = tracer
|
||||
|
||||
# Pause / resume state for async RL workflows.
|
||||
self._pause_cond = asyncio.Condition()
|
||||
self._paused = False
|
||||
|
||||
# EngineCore (starts the engine in background process).
|
||||
self.engine_core = EngineCoreClient.make_async_mp_client(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=executor_class,
|
||||
log_stats=self.log_stats,
|
||||
client_addresses=client_addresses,
|
||||
client_count=client_count,
|
||||
client_index=client_index,
|
||||
)
|
||||
|
||||
# Loggers.
|
||||
self.logger_manager: StatLoggerManager | None = None
|
||||
if self.log_stats:
|
||||
self.logger_manager = StatLoggerManager(
|
||||
vllm_config=vllm_config,
|
||||
engine_idxs=self.engine_core.engine_ranks_managed,
|
||||
custom_stat_loggers=stat_loggers,
|
||||
enable_default_loggers=log_stats,
|
||||
client_count=client_count,
|
||||
)
|
||||
self.logger_manager.log_engine_initialized()
|
||||
|
||||
self.output_handler: asyncio.Task | None = None
|
||||
try:
|
||||
# Start output handler eagerly if we are in the asyncio eventloop.
|
||||
asyncio.get_running_loop()
|
||||
self._run_output_handler()
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
# Use profiler_config from vllm_config (new way, aligned with vllm v1)
|
||||
if vllm_config.profiler_config.profiler == "torch" and not vllm_config.profiler_config.ignore_frontend:
|
||||
profiler_dir = vllm_config.profiler_config.torch_profiler_dir
|
||||
logger.info(
|
||||
"Torch profiler enabled. AsyncOmniLLM CPU traces will be collected under %s",
|
||||
profiler_dir,
|
||||
)
|
||||
worker_name = f"{socket.gethostname()}_{os.getpid()}.async_omni_llm"
|
||||
self.profiler = torch.profiler.profile(
|
||||
activities=[
|
||||
torch.profiler.ProfilerActivity.CPU,
|
||||
],
|
||||
with_stack=vllm_config.profiler_config.torch_profiler_with_stack,
|
||||
on_trace_ready=torch.profiler.tensorboard_trace_handler(
|
||||
profiler_dir,
|
||||
worker_name=worker_name,
|
||||
use_gzip=vllm_config.profiler_config.torch_profiler_use_gzip,
|
||||
),
|
||||
)
|
||||
else:
|
||||
self.profiler = None
|
||||
|
||||
@classmethod
|
||||
@deprecate_kwargs(
|
||||
"disable_log_requests",
|
||||
additional_message=("This argument will have no effect. Use `enable_log_requests` instead."),
|
||||
)
|
||||
def from_vllm_config(
|
||||
cls,
|
||||
vllm_config: VllmConfig,
|
||||
engine_args: AsyncOmniEngineArgs,
|
||||
start_engine_loop: bool = True,
|
||||
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
|
||||
stat_loggers: list[StatLoggerFactory] | None = None,
|
||||
enable_log_requests: bool = False,
|
||||
disable_log_stats: bool = False,
|
||||
client_addresses: dict[str, str] | None = None,
|
||||
client_count: int = 1,
|
||||
client_index: int = 0,
|
||||
disable_log_requests: bool = True, # Deprecated, will be removed
|
||||
) -> "AsyncLLM":
|
||||
# Create the LLMEngine.
|
||||
return cls(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=Executor.get_class(vllm_config),
|
||||
start_engine_loop=start_engine_loop,
|
||||
stat_loggers=stat_loggers,
|
||||
log_requests=enable_log_requests,
|
||||
log_stats=not disable_log_stats,
|
||||
usage_context=usage_context,
|
||||
client_addresses=client_addresses,
|
||||
client_count=client_count,
|
||||
client_index=client_index,
|
||||
engine_args=engine_args,
|
||||
)
|
||||
@@ -8,37 +8,20 @@ diffusion models (e.g., Qwen-Image) through the same CLI interface.
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
from typing import Any
|
||||
|
||||
import msgspec.msgpack
|
||||
import uvloop
|
||||
import zmq
|
||||
from vllm.entrypoints.cli.types import CLISubcommand
|
||||
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
|
||||
from vllm.entrypoints.utils import VLLM_SUBCMD_PARSER_EPILOG
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.network_utils import make_zmq_socket
|
||||
from vllm.v1.utils import get_engine_client_zmq_addr
|
||||
|
||||
from vllm_omni.distributed.omni_connectors import (
|
||||
get_connectors_config_for_stage,
|
||||
load_omni_transfer_config,
|
||||
)
|
||||
from vllm_omni.distributed.omni_connectors.utils.initialization import (
|
||||
resolve_omni_kv_config_for_stage,
|
||||
)
|
||||
from vllm_omni.entrypoints.cli.logo import log_logo
|
||||
from vllm_omni.entrypoints.omni import OmniBase, omni_snapshot_download
|
||||
from vllm_omni.entrypoints.omni_stage import OmniStage
|
||||
from vllm_omni.entrypoints.openai.api_server import omni_run_server
|
||||
from vllm_omni.entrypoints.utils import inject_omni_kv_config
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
HANDSHAKE_TIMEOUT_MINS = 5
|
||||
|
||||
DESCRIPTION = """Launch a local OpenAI-compatible API server to serve Omni models
|
||||
via HTTP. Supports both multi-stage LLM models and diffusion models.
|
||||
|
||||
@@ -372,123 +355,33 @@ class OmniServeCommand(CLISubcommand):
|
||||
|
||||
|
||||
def _create_default_diffusion_stage_cfg(args: argparse.Namespace) -> list[dict[str, Any]]:
|
||||
omni_base = OmniBase.__new__(OmniBase)
|
||||
return omni_base._create_default_diffusion_stage_cfg(vars(args))
|
||||
"""Create default diffusion stage configuration.
|
||||
|
||||
Uses AsyncOmniEngine's implementation which doesn't have OmegaConf
|
||||
compatibility issues.
|
||||
"""
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
|
||||
return AsyncOmniEngine._create_default_diffusion_stage_cfg(vars(args))
|
||||
|
||||
|
||||
def run_headless(args: argparse.Namespace) -> None:
|
||||
if args.api_server_count is not None and args.api_server_count > 1:
|
||||
raise ValueError("api_server_count can't be set in headless mode")
|
||||
if args.worker_backend != "multi_process":
|
||||
raise ValueError("headless mode requires worker_backend=multi_process")
|
||||
"""Run a single stage in headless mode.
|
||||
|
||||
model = omni_snapshot_download(args.model)
|
||||
.. deprecated:: 0.x.x
|
||||
Headless mode is deprecated and will be removed in a future version.
|
||||
It is only compatible with the old OmniStage-based runtime.
|
||||
The current AsyncOmniEngine-based runtime does not support headless mode.
|
||||
|
||||
omni_base = OmniBase.__new__(OmniBase)
|
||||
args_dict = vars(args).copy()
|
||||
args_dict["model"] = model
|
||||
config_path, stage_configs = omni_base._resolve_stage_configs(model, args_dict)
|
||||
|
||||
single_stage_id = args.stage_id
|
||||
if single_stage_id is None:
|
||||
if len(stage_configs) != 1:
|
||||
raise ValueError("--stage-id is required in headless mode for multi-stage configs")
|
||||
single_stage_id = getattr(stage_configs[0], "stage_id", 0)
|
||||
|
||||
stage_config = None
|
||||
for cfg in stage_configs:
|
||||
if getattr(cfg, "stage_id", None) == single_stage_id:
|
||||
stage_config = cfg
|
||||
break
|
||||
if stage_config is None:
|
||||
raise ValueError(f"No stage matches stage_id={single_stage_id}.")
|
||||
|
||||
# TODO(wuhang): Support connectors config by cli
|
||||
transfer_config = load_omni_transfer_config(config_path, default_shm_threshold=args.shm_threshold_bytes)
|
||||
connectors_config = get_connectors_config_for_stage(transfer_config, single_stage_id)
|
||||
|
||||
omni_master_address = args.omni_master_address
|
||||
omni_master_port = args.omni_master_port
|
||||
|
||||
# Perform handshake with orchestrator to get dynamically allocated endpoints
|
||||
with zmq.Context() as zmq_ctx:
|
||||
handshake_endpoint = get_engine_client_zmq_addr(
|
||||
local_only=False, host=omni_master_address, port=omni_master_port
|
||||
)
|
||||
|
||||
with make_zmq_socket(zmq_ctx, handshake_endpoint, zmq.REQ, bind=False, linger=5000) as handshake_socket:
|
||||
# TODO(wuhang): Define protocol in python dataclass.
|
||||
handshake_msg = {"type": "handshake", "stage_id": single_stage_id}
|
||||
handshake_socket.send(msgspec.msgpack.encode(handshake_msg))
|
||||
|
||||
# Wait for response with timeout
|
||||
if not handshake_socket.poll(timeout=HANDSHAKE_TIMEOUT_MINS * 60_000):
|
||||
raise RuntimeError(
|
||||
f"Handshake timeout ({HANDSHAKE_TIMEOUT_MINS} minutes) for stage-{single_stage_id} "
|
||||
f"at {handshake_endpoint}"
|
||||
)
|
||||
|
||||
try:
|
||||
response = msgspec.msgpack.decode(handshake_socket.recv())
|
||||
except msgspec.DecodeError as exc:
|
||||
raise RuntimeError(
|
||||
f"Handshake decode failed for stage-{single_stage_id} at {handshake_endpoint}: {exc}"
|
||||
) from exc
|
||||
except Exception as exc: # pragma: no cover - unexpected decode errors
|
||||
raise RuntimeError(
|
||||
f"Unexpected error decoding handshake for stage-{single_stage_id} at {handshake_endpoint}: {exc}"
|
||||
) from exc
|
||||
|
||||
if not response["ok"]:
|
||||
error_msg = response["error"]
|
||||
raise RuntimeError(f"Handshake failed for stage-{single_stage_id}: {error_msg}")
|
||||
|
||||
in_endpoint, out_endpoint = response["in_endpoint"], response["out_endpoint"]
|
||||
|
||||
logger.info(
|
||||
f"[Headless] Stage-{single_stage_id} received endpoints via handshake: "
|
||||
f"in={in_endpoint}, out={out_endpoint}"
|
||||
)
|
||||
|
||||
shutdown_requested = False
|
||||
|
||||
def signal_handler(signum, frame):
|
||||
nonlocal shutdown_requested
|
||||
if shutdown_requested:
|
||||
return
|
||||
shutdown_requested = True
|
||||
raise SystemExit
|
||||
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
stage = OmniStage(stage_config, stage_init_timeout=args.stage_init_timeout)
|
||||
stage.attach_queues(in_endpoint, out_endpoint)
|
||||
|
||||
# Inject YAML-resolved connector config into omni_kv_config for in-engine usage.
|
||||
try:
|
||||
omni_conn_cfg, omni_from, omni_to = resolve_omni_kv_config_for_stage(transfer_config, single_stage_id)
|
||||
if omni_conn_cfg:
|
||||
inject_omni_kv_config(stage, omni_conn_cfg, omni_from, omni_to) # type: ignore
|
||||
except Exception as e:
|
||||
logger.debug("[Headless] Failed to inject omni connector config into stage-%s: %s", single_stage_id, e)
|
||||
|
||||
old_env = os.environ.get("VLLM_LOGGING_PREFIX")
|
||||
os.environ["VLLM_LOGGING_PREFIX"] = f"[Stage-{single_stage_id}] {'' if old_env is None else old_env}"
|
||||
try:
|
||||
stage.init_stage_worker(
|
||||
model,
|
||||
is_async=True,
|
||||
shm_threshold_bytes=int(args.shm_threshold_bytes),
|
||||
batch_timeout=int(args.batch_timeout),
|
||||
connectors_config=connectors_config,
|
||||
worker_backend="multi_process",
|
||||
ignore_runtime_config=True,
|
||||
)
|
||||
if stage._proc is not None:
|
||||
stage._proc.join()
|
||||
finally:
|
||||
stage.stop_stage_worker()
|
||||
Raises:
|
||||
RuntimeError: Always raises an error indicating headless mode is deprecated.
|
||||
"""
|
||||
raise RuntimeError(
|
||||
"Headless mode is deprecated and not supported in the current runtime. "
|
||||
"Please use the standard orchestrator mode (without --headless flag). "
|
||||
"If you need distributed deployment, consider using Ray backend or "
|
||||
"other distributed serving solutions."
|
||||
)
|
||||
|
||||
|
||||
def cmd_init() -> list[CLISubcommand]:
|
||||
|
||||
+110
-1381
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,290 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
import types
|
||||
import weakref
|
||||
from collections.abc import Sequence
|
||||
from pprint import pformat
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
import huggingface_hub
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.entrypoints.client_request_state import ClientRequestState
|
||||
from vllm_omni.entrypoints.utils import get_final_stage_id_for_e2e
|
||||
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.engine.arg_utils import OmniEngineArgs
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _weak_shutdown_engine(engine: AsyncOmniEngine) -> None:
|
||||
"""Best-effort engine cleanup for GC finalization."""
|
||||
try:
|
||||
engine.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def omni_snapshot_download(model_id: str) -> str:
|
||||
if os.path.exists(model_id):
|
||||
return model_id
|
||||
|
||||
# TODO: this is just a workaround for quickly use modelscope, we should support
|
||||
# modelscope in weight loading feature instead of using `snapshot_download`
|
||||
if os.environ.get("VLLM_USE_MODELSCOPE", False):
|
||||
from modelscope.hub.snapshot_download import snapshot_download
|
||||
|
||||
return snapshot_download(model_id)
|
||||
|
||||
try:
|
||||
download_weights_from_hf_specific(
|
||||
model_name_or_path=model_id,
|
||||
cache_dir=None,
|
||||
allow_patterns=["*"],
|
||||
require_all=True,
|
||||
)
|
||||
except huggingface_hub.errors.RepositoryNotFoundError:
|
||||
logger.warning("Repository not found for '%s'.", model_id)
|
||||
|
||||
return model_id
|
||||
|
||||
|
||||
OutputMessageHandleResult = tuple[Literal[True], None, None, None] | tuple[Literal[False], str, int, ClientRequestState]
|
||||
|
||||
|
||||
class OmniBase:
|
||||
"""Shared runtime foundation for AsyncOmni and Omni."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
engine_args: OmniEngineArgs | None = kwargs.pop("engine_args", None)
|
||||
stage_init_timeout = kwargs.pop("stage_init_timeout", 300)
|
||||
init_timeout = kwargs.pop("init_timeout", 600)
|
||||
log_stats = kwargs.pop("log_stats", False)
|
||||
async_chunk = kwargs.pop("async_chunk", False)
|
||||
output_modalities = kwargs.pop("output_modalities", None)
|
||||
|
||||
if "log_requests" in kwargs:
|
||||
raise TypeError("`log_requests` has been removed in Omni/AsyncOmni. Use `log_stats`.")
|
||||
model = omni_snapshot_download(model)
|
||||
self.model = model
|
||||
self.log_stats = log_stats
|
||||
self.async_chunk = async_chunk
|
||||
self.output_modalities = output_modalities or []
|
||||
|
||||
logger.info("[%s] Initializing with model %s", self.__class__.__name__, model)
|
||||
st = time.time()
|
||||
self.engine = AsyncOmniEngine(
|
||||
model=model,
|
||||
engine_args=engine_args,
|
||||
init_timeout=init_timeout,
|
||||
stage_init_timeout=stage_init_timeout,
|
||||
**kwargs,
|
||||
)
|
||||
self._shutdown_called = False
|
||||
self._weak_finalizer = weakref.finalize(self, _weak_shutdown_engine, self.engine)
|
||||
et = time.time()
|
||||
logger.info("[%s] AsyncOmniEngine initialized in %.2f seconds", self.__class__.__name__, et - st)
|
||||
self.async_chunk = bool(self.async_chunk or getattr(self.engine, "async_chunk", False))
|
||||
|
||||
self.request_states: dict[str, ClientRequestState] = {}
|
||||
|
||||
self.default_sampling_params_list = self.engine.default_sampling_params_list
|
||||
if not self.output_modalities:
|
||||
self.output_modalities = [
|
||||
self.engine.get_stage_metadata(i).get("final_output_type") for i in range(self.engine.num_stages)
|
||||
]
|
||||
|
||||
self._stage_meta_list = [
|
||||
types.SimpleNamespace(**self.engine.get_stage_metadata(i)) for i in range(self.engine.num_stages)
|
||||
]
|
||||
|
||||
logger.info(
|
||||
"[%s] Initialized with %s stages for model %s",
|
||||
self.__class__.__name__,
|
||||
self.engine.num_stages,
|
||||
model,
|
||||
)
|
||||
|
||||
@property
|
||||
def num_stages(self) -> int:
|
||||
return self.engine.num_stages
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
return self.engine.is_alive()
|
||||
|
||||
def check_health(self) -> None:
|
||||
if not self.engine.is_alive():
|
||||
raise EngineDeadError("Orchestrator process is not alive")
|
||||
|
||||
def resolve_sampling_params_list(
|
||||
self,
|
||||
sampling_params_list: Sequence[Any] | Any | None,
|
||||
) -> Sequence[Any]:
|
||||
if sampling_params_list is None:
|
||||
normalized = self.default_sampling_params_list
|
||||
elif isinstance(sampling_params_list, Sequence) and not isinstance(sampling_params_list, (str, bytes)):
|
||||
normalized = sampling_params_list
|
||||
elif self.num_stages == 1:
|
||||
normalized = [sampling_params_list]
|
||||
else:
|
||||
raise ValueError(f"Expected {self.num_stages} sampling params, got a single sampling params object")
|
||||
if len(normalized) != self.num_stages:
|
||||
raise ValueError(f"Expected {self.num_stages} sampling params, got {len(normalized)}")
|
||||
return normalized
|
||||
|
||||
def _log_summary_and_cleanup(self, request_id: str) -> None:
|
||||
req_state = self.request_states.get(request_id)
|
||||
try:
|
||||
if req_state is None or req_state.metrics is None:
|
||||
return
|
||||
summary = req_state.metrics.build_and_log_summary()
|
||||
logger.info("[Summary] %s", pformat(summary, sort_dicts=False))
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"[%s] Failed to build/log summary for req=%s",
|
||||
self.__class__.__name__,
|
||||
request_id,
|
||||
)
|
||||
finally:
|
||||
self.request_states.pop(request_id, None)
|
||||
|
||||
def _compute_final_stage_id(self, output_modalities: list[str] | None) -> int:
|
||||
return get_final_stage_id_for_e2e(
|
||||
output_modalities,
|
||||
self.output_modalities,
|
||||
self._stage_meta_list,
|
||||
)
|
||||
|
||||
def _process_stage_metrics_message(self, msg: dict[str, Any]) -> None:
|
||||
req_id = msg.get("request_id")
|
||||
req_state = self.request_states.get(req_id)
|
||||
if req_state is None or req_state.metrics is None:
|
||||
return
|
||||
_m = msg.get("metrics")
|
||||
if _m is None:
|
||||
return
|
||||
stage_id = msg.get("stage_id", 0)
|
||||
req_state.metrics.on_stage_metrics(stage_id, req_id, _m)
|
||||
submit_ts = msg.get("stage_submit_ts")
|
||||
now = time.time()
|
||||
if req_state.metrics.stage_first_ts[stage_id] is None:
|
||||
req_state.metrics.stage_first_ts[stage_id] = submit_ts if submit_ts is not None else now
|
||||
req_state.metrics.stage_last_ts[stage_id] = max(req_state.metrics.stage_last_ts[stage_id] or 0.0, now)
|
||||
|
||||
def _handle_output_message(
|
||||
self,
|
||||
msg: dict[str, Any] | None,
|
||||
) -> OutputMessageHandleResult:
|
||||
"""Handle one Orchestrator output-queue message."""
|
||||
if msg is None:
|
||||
return True, None, None, None
|
||||
|
||||
msg_type = msg.get("type")
|
||||
if msg_type == "stage_metrics":
|
||||
self._process_stage_metrics_message(msg)
|
||||
return True, None, None, None
|
||||
|
||||
if msg_type == "error":
|
||||
raise RuntimeError(msg.get("error", "Orchestrator returned an error message"))
|
||||
|
||||
if msg_type != "output":
|
||||
logger.warning("[%s] got unexpected msg type: %s", self.__class__.__name__, msg_type)
|
||||
return True, None, None, None
|
||||
|
||||
req_id = msg.get("request_id")
|
||||
if req_id is None:
|
||||
logger.warning("[%s] got output message without request_id", self.__class__.__name__)
|
||||
return True, None, None, None
|
||||
|
||||
stage_id = msg.get("stage_id")
|
||||
if stage_id is None:
|
||||
logger.warning("[%s] got output message without stage_id for req=%s", self.__class__.__name__, req_id)
|
||||
return True, None, None, None
|
||||
|
||||
req_state = self.request_states.get(req_id)
|
||||
if req_state is None:
|
||||
logger.debug(
|
||||
"[%s] dropping output for unknown req %s",
|
||||
self.__class__.__name__,
|
||||
req_id,
|
||||
)
|
||||
return True, None, None, None
|
||||
|
||||
req_state.stage_id = stage_id
|
||||
|
||||
return False, req_id, stage_id, req_state
|
||||
|
||||
def _process_single_result(
|
||||
self,
|
||||
result: dict[str, Any],
|
||||
stage_id: int,
|
||||
metrics: OrchestratorMetrics,
|
||||
req_start_ts: dict[str, float],
|
||||
wall_start_ts: float,
|
||||
final_stage_id_for_e2e: int,
|
||||
) -> OmniRequestOutput | None:
|
||||
req_id = result.get("request_id")
|
||||
engine_outputs = result.get("engine_outputs")
|
||||
finished = engine_outputs.finished
|
||||
|
||||
submit_ts = result.get("stage_submit_ts")
|
||||
now = time.time()
|
||||
if metrics.stage_first_ts[stage_id] is None:
|
||||
metrics.stage_first_ts[stage_id] = submit_ts if submit_ts is not None else now
|
||||
metrics.stage_last_ts[stage_id] = max(metrics.stage_last_ts[stage_id] or 0.0, now)
|
||||
|
||||
_m = result.get("metrics")
|
||||
if finished and _m is not None:
|
||||
metrics.on_stage_metrics(stage_id, req_id, _m)
|
||||
|
||||
stage_meta = self.engine.get_stage_metadata(stage_id)
|
||||
if not stage_meta["final_output"]:
|
||||
return None
|
||||
|
||||
try:
|
||||
rid_key = str(req_id)
|
||||
if stage_id == final_stage_id_for_e2e and rid_key not in metrics.e2e_done and finished:
|
||||
metrics.on_finalize_request(
|
||||
stage_id,
|
||||
req_id,
|
||||
req_start_ts.get(req_id, wall_start_ts),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("[%s] Finalize request handling error", self.__class__.__name__)
|
||||
|
||||
images = getattr(engine_outputs, "images", []) if stage_meta["final_output_type"] == "image" else []
|
||||
return OmniRequestOutput(
|
||||
stage_id=stage_id,
|
||||
final_output_type=stage_meta["final_output_type"],
|
||||
request_output=engine_outputs,
|
||||
images=images,
|
||||
)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
logger.info("[%s] Shutting down", self.__class__.__name__)
|
||||
self._shutdown_base()
|
||||
|
||||
def close(self) -> None:
|
||||
self.shutdown()
|
||||
|
||||
def _shutdown_base(self) -> None:
|
||||
if getattr(self, "_shutdown_called", False):
|
||||
return
|
||||
self._shutdown_called = True
|
||||
finalizer = getattr(self, "_weak_finalizer", None)
|
||||
if finalizer is not None and finalizer.alive:
|
||||
finalizer.detach()
|
||||
self.engine.shutdown()
|
||||
@@ -1,169 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Sequence
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig, TransformerConfig
|
||||
from vllm_omni.diffusion.diffusion_engine import DiffusionEngine
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class OmniDiffusion:
|
||||
"""
|
||||
It is the main class to interact with vLLM-Omni diffusion models.
|
||||
It acts as a high-level interface that prepares requests and
|
||||
delegates the actual diffusion process to the DiffusionEngine.
|
||||
|
||||
You can pass either an `OmniDiffusionConfig` via `od_config`, or
|
||||
pass kwargs such as `model="Qwen/Qwen-Image"`,
|
||||
which will be forwarded to `OmniDiffusionConfig.from_kwargs`.
|
||||
"""
|
||||
|
||||
def __init__(self, od_config: OmniDiffusionConfig | None = None, **kwargs):
|
||||
# Capture stage info from kwargs before they might be filtered out
|
||||
stage_id = kwargs.get("stage_id")
|
||||
engine_input_source = kwargs.get("engine_input_source")
|
||||
cfg_kv_collect_func = kwargs.pop("cfg_kv_collect_func", None)
|
||||
|
||||
if od_config is None:
|
||||
od_config = OmniDiffusionConfig.from_kwargs(**kwargs)
|
||||
elif isinstance(od_config, dict):
|
||||
# If config is dict, check it too (priority to kwargs if both exist)
|
||||
if stage_id is None:
|
||||
stage_id = od_config.get("stage_id")
|
||||
if engine_input_source is None:
|
||||
engine_input_source = od_config.get("engine_input_source")
|
||||
od_config = OmniDiffusionConfig.from_kwargs(**od_config)
|
||||
|
||||
self.od_config = od_config
|
||||
|
||||
# Inject stage info into omni_kv_config if present
|
||||
if stage_id is not None:
|
||||
self.od_config.omni_kv_config.setdefault("stage_id", stage_id)
|
||||
if engine_input_source is not None:
|
||||
self.od_config.omni_kv_config.setdefault("engine_input_source", engine_input_source)
|
||||
|
||||
# Detect model class and load config
|
||||
# Diffusers-style models expose `model_index.json` with `_class_name`.
|
||||
# Non-diffusers models (e.g. Bagel, NextStep, GLM-Image) only have `config.json`,
|
||||
# so we fall back to reading that and mapping model_type manually.
|
||||
try:
|
||||
config_dict = get_hf_file_to_dict(
|
||||
"model_index.json",
|
||||
od_config.model,
|
||||
)
|
||||
|
||||
if config_dict is None:
|
||||
raise FileNotFoundError("model_index.json not found")
|
||||
|
||||
if od_config.model_class_name is None:
|
||||
od_config.model_class_name = config_dict.get("_class_name", None)
|
||||
od_config.update_multimodal_support()
|
||||
|
||||
if od_config.model_class_name == "DreamIDOmniPipeline":
|
||||
od_config.model_config = config_dict
|
||||
else:
|
||||
tf_config_dict = get_hf_file_to_dict(
|
||||
"transformer/config.json",
|
||||
od_config.model,
|
||||
)
|
||||
od_config.tf_model_config = TransformerConfig.from_dict(tf_config_dict)
|
||||
|
||||
except (AttributeError, OSError, ValueError, FileNotFoundError):
|
||||
cfg = get_hf_file_to_dict("config.json", od_config.model)
|
||||
if cfg is None:
|
||||
raise ValueError(f"Could not find config.json or model_index.json for model {od_config.model}")
|
||||
|
||||
# Map model_type or architecture to pipeline class
|
||||
model_type = cfg.get("model_type")
|
||||
architectures = cfg.get("architectures") or []
|
||||
pipeline_class = None
|
||||
# Bagel/NextStep models don't have a model_index.json, so we set the pipeline class name manually
|
||||
if model_type == "bagel" or "BagelForConditionalGeneration" in architectures:
|
||||
pipeline_class = "BagelPipeline"
|
||||
elif model_type == "nextstep":
|
||||
if od_config.model_class_name is None:
|
||||
pipeline_class = "NextStep11Pipeline"
|
||||
elif model_type == "glm-image" or "GlmImageForConditionalGeneration" in architectures:
|
||||
pipeline_class = "GlmImagePipeline"
|
||||
elif architectures and len(architectures) == 1:
|
||||
pipeline_class = architectures[0]
|
||||
|
||||
if pipeline_class is None:
|
||||
raise ValueError(f"Unknown model type: {model_type}, architectures: {architectures}")
|
||||
|
||||
if od_config.model_class_name is None:
|
||||
od_config.model_class_name = pipeline_class
|
||||
od_config.tf_model_config = TransformerConfig().from_dict(cfg)
|
||||
od_config.update_multimodal_support()
|
||||
|
||||
if cfg_kv_collect_func is not None:
|
||||
od_config.cfg_kv_collect_func = cfg_kv_collect_func
|
||||
|
||||
self.engine: DiffusionEngine = DiffusionEngine.make_engine(od_config)
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompts: OmniPromptType | Sequence[OmniPromptType],
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
request_ids: list[str] = [],
|
||||
) -> list[OmniRequestOutput]:
|
||||
_t0 = time.perf_counter()
|
||||
if isinstance(prompts, (str, dict)):
|
||||
prompts = [prompts]
|
||||
else:
|
||||
prompts = list(prompts)
|
||||
|
||||
# Check if request_id is provided in kwargs
|
||||
if len(request_ids) < len(prompts):
|
||||
request_ids.extend(f"{i + len(request_ids)}_{uuid.uuid4()}" for i in range(len(prompts) - len(request_ids)))
|
||||
|
||||
request = OmniDiffusionRequest(prompts, sampling_params, request_ids)
|
||||
result = self._run_engine(request)
|
||||
_t_ms = (time.perf_counter() - _t0) * 1000
|
||||
logger.info("OmniDiffusion.generate total: %.2f ms", _t_ms)
|
||||
return result
|
||||
|
||||
def _run_engine(self, request: OmniDiffusionRequest) -> list[OmniRequestOutput]:
|
||||
return self.engine.step(request)
|
||||
|
||||
def close(self) -> None:
|
||||
self.engine.close()
|
||||
|
||||
def __del__(self): # pragma: no cover - best effort cleanup
|
||||
try:
|
||||
self.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def start_profile(self, trace_filename: str | None = None) -> None:
|
||||
"""Start profiling for the diffusion model.
|
||||
|
||||
Args:
|
||||
trace_filename: Optional base filename for trace files.
|
||||
If None, a timestamp-based name will be generated.
|
||||
"""
|
||||
if hasattr(self, "engine") and self.engine:
|
||||
self.engine.start_profile(trace_filename)
|
||||
else:
|
||||
raise RuntimeError("Diffusion engine not initialized")
|
||||
|
||||
def stop_profile(self) -> dict:
|
||||
"""Stop profiling and return profiling results.
|
||||
|
||||
Returns:
|
||||
Dictionary containing paths to trace and table files.
|
||||
"""
|
||||
if hasattr(self, "engine") and self.engine:
|
||||
return self.engine.stop_profile()
|
||||
else:
|
||||
raise RuntimeError("Diffusion engine not initialized")
|
||||
@@ -1,275 +0,0 @@
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import Any
|
||||
|
||||
import cloudpickle
|
||||
from pydantic import ValidationError
|
||||
from tqdm import tqdm
|
||||
|
||||
# External library imports (vLLM)
|
||||
from vllm.config import CompilationConfig, StructuredOutputsConfig, is_init_field
|
||||
from vllm.entrypoints.llm import LLM
|
||||
from vllm.inputs import ProcessorInputs, PromptType
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import PoolingRequestOutput, RequestOutput
|
||||
from vllm.plugins.io_processors import get_io_processor
|
||||
from vllm.renderers.inputs.preprocess import parse_model_prompt
|
||||
from vllm.usage.usage_lib import UsageContext
|
||||
from vllm.utils.counter import Counter
|
||||
from vllm.v1.engine.llm_engine import LLMEngine
|
||||
|
||||
from vllm_omni.distributed.omni_connectors import initialize_orchestrator_connectors
|
||||
|
||||
# Internal imports (our code)
|
||||
from vllm_omni.engine.arg_utils import OmniEngineArgs
|
||||
from vllm_omni.engine.input_processor import OmniInputProcessor, reinject_omni_fields
|
||||
from vllm_omni.engine.output_processor import MultimodalOutputProcessor
|
||||
from vllm_omni.entrypoints.utils import (
|
||||
filter_dataclass_kwargs,
|
||||
resolve_model_config_path,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class OmniLLM(LLM):
|
||||
"""Main entry point for vLLM-Omni inference.
|
||||
|
||||
This class extends the base vLLM LLM class with omni-specific
|
||||
processors for handling multimodal inputs and outputs. It provides
|
||||
configuration loading for multi-stage pipelines, while stage management
|
||||
is handled by the Omni class.
|
||||
|
||||
Args:
|
||||
model: Model name or path to load
|
||||
log_stats: Whether to enable statistics logging
|
||||
compilation_config: Optional compilation configuration. Can be an
|
||||
integer (compilation level), dict, or CompilationConfig instance.
|
||||
hf_overrides: Optional HuggingFace model configuration overrides
|
||||
structured_outputs_config: Optional structured outputs configuration.
|
||||
Can be a dict or StructuredOutputsConfig instance.
|
||||
init_sleep_seconds: Number of seconds to sleep between starting
|
||||
each stage process during initialization (used by Omni class)
|
||||
shm_threshold_bytes: Threshold in bytes for using shared memory
|
||||
for IPC. Objects larger than this threshold will use shared memory.
|
||||
batch_timeout: Timeout in seconds for batching requests within a stage
|
||||
init_timeout: Timeout in seconds for waiting for all stages to initialize
|
||||
**kwargs: Additional keyword arguments passed to the base LLM class
|
||||
and engine
|
||||
|
||||
Example:
|
||||
>>> llm = OmniLLM(model="Qwen/Qwen2.5-Omni-7B")
|
||||
>>> # Stage management is handled by Omni class
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
log_stats: bool = False,
|
||||
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,
|
||||
init_sleep_seconds: int = 20,
|
||||
shm_threshold_bytes: int = 65536,
|
||||
batch_timeout: int = 10,
|
||||
init_timeout: int = 300,
|
||||
**kwargs: Any,
|
||||
):
|
||||
"""LLM constructor with omni-specific configuration loading."""
|
||||
# Store stage management parameters (used by Omni class)
|
||||
self.worker_backend = kwargs.get("worker_backend", "multi_process")
|
||||
self.ray_address = kwargs.get("ray_address", None)
|
||||
self.batch_timeout = batch_timeout
|
||||
self.log_stats: bool = bool(log_stats)
|
||||
|
||||
# Resolve model config path for connectors
|
||||
self.config_path = resolve_model_config_path(model)
|
||||
|
||||
# Initialize connectors
|
||||
self.omni_transfer_config, self.connectors = initialize_orchestrator_connectors(
|
||||
self.config_path, worker_backend=self.worker_backend, shm_threshold_bytes=shm_threshold_bytes
|
||||
)
|
||||
|
||||
# Initialize LLM engine
|
||||
if "disable_log_stats" not in kwargs:
|
||||
kwargs["disable_log_stats"] = True
|
||||
|
||||
if "worker_cls" in kwargs:
|
||||
worker_cls = kwargs["worker_cls"]
|
||||
# if the worker_cls is not qualified string name,
|
||||
# we serialize it using cloudpickle to avoid pickling issues
|
||||
if isinstance(worker_cls, type):
|
||||
kwargs["worker_cls"] = cloudpickle.dumps(worker_cls)
|
||||
|
||||
if "kv_transfer_config" in kwargs and isinstance(kwargs["kv_transfer_config"], dict):
|
||||
from vllm.config.kv_transfer import KVTransferConfig
|
||||
|
||||
raw_config_dict = kwargs["kv_transfer_config"]
|
||||
try:
|
||||
kwargs["kv_transfer_config"] = KVTransferConfig(**raw_config_dict)
|
||||
except ValidationError as e:
|
||||
logger.error(
|
||||
"Failed to convert 'kv_transfer_config' dict to KVTransferConfig object. Dict: %s. Error: %s",
|
||||
raw_config_dict,
|
||||
e,
|
||||
)
|
||||
raise ValueError(f"Invalid 'kv_transfer_config' provided: {e}") from e
|
||||
|
||||
# Extract omni_kv_config from kwargs if present (injected by Omni)
|
||||
omni_kv_config = kwargs.pop("omni_kv_config", None)
|
||||
|
||||
if compilation_config is not None:
|
||||
if isinstance(compilation_config, int):
|
||||
compilation_config_instance = CompilationConfig(level=compilation_config)
|
||||
elif isinstance(compilation_config, dict):
|
||||
compilation_config_instance = CompilationConfig(
|
||||
**{k: v for k, v in compilation_config.items() if is_init_field(CompilationConfig, k)}
|
||||
)
|
||||
else:
|
||||
compilation_config_instance = compilation_config
|
||||
else:
|
||||
compilation_config_instance = CompilationConfig()
|
||||
|
||||
if structured_outputs_config is not None:
|
||||
if isinstance(structured_outputs_config, dict):
|
||||
structured_outputs_instance = StructuredOutputsConfig(
|
||||
**{k: v for k, v in structured_outputs_config.items() if is_init_field(StructuredOutputsConfig, k)}
|
||||
)
|
||||
else:
|
||||
structured_outputs_instance = structured_outputs_config
|
||||
else:
|
||||
structured_outputs_instance = StructuredOutputsConfig()
|
||||
|
||||
engine_args = OmniEngineArgs(
|
||||
model=model,
|
||||
compilation_config=compilation_config_instance,
|
||||
structured_outputs_config=structured_outputs_instance,
|
||||
omni_kv_config=omni_kv_config,
|
||||
hf_overrides=hf_overrides or {},
|
||||
**filter_dataclass_kwargs(OmniEngineArgs, kwargs),
|
||||
)
|
||||
|
||||
# Create the Engine (autoselects V0 vs V1)
|
||||
self.llm_engine = LLMEngine.from_engine_args(engine_args=engine_args, usage_context=UsageContext.LLM_CLASS)
|
||||
self.llm_engine.output_processor = MultimodalOutputProcessor(
|
||||
tokenizer=self.llm_engine.tokenizer,
|
||||
log_stats=self.llm_engine.log_stats,
|
||||
engine_core_output_type=engine_args.engine_output_type,
|
||||
)
|
||||
self.llm_engine.input_processor = OmniInputProcessor(vllm_config=self.llm_engine.vllm_config)
|
||||
self.engine_class = type(self.llm_engine)
|
||||
|
||||
self.request_counter = Counter()
|
||||
self.default_sampling_params: dict[str, Any] | None = None
|
||||
|
||||
supported_tasks = self.llm_engine.get_supported_tasks() # type: ignore
|
||||
|
||||
logger.info("Supported_tasks: %s", supported_tasks)
|
||||
|
||||
self.supported_tasks = supported_tasks
|
||||
|
||||
# Keep parity with vLLM's LLM initialization fields so inherited
|
||||
# generate/chat preprocessing paths work as expected.
|
||||
self.renderer = self.llm_engine.renderer
|
||||
# Load the Input/Output processor plugin if any
|
||||
io_processor_plugin = self.llm_engine.model_config.io_processor_plugin
|
||||
self.io_processor = get_io_processor(self.llm_engine.vllm_config, io_processor_plugin)
|
||||
self.model_config = self.llm_engine.model_config
|
||||
self.input_processor = self.llm_engine.input_processor
|
||||
|
||||
# Parity with upstream LLM for pooling/classify entrypoints
|
||||
chat_template = kwargs.get("chat_template", None)
|
||||
from vllm.entrypoints.chat_utils import ChatTemplateConfig, load_chat_template
|
||||
from vllm.entrypoints.pooling.io_processor_factories import init_pooling_io_processors
|
||||
|
||||
self.chat_template = load_chat_template(chat_template)
|
||||
self.chat_template_config = ChatTemplateConfig(chat_template=self.chat_template)
|
||||
self.init_pooling_io_processors = init_pooling_io_processors(
|
||||
supported_tasks=supported_tasks,
|
||||
model_config=self.model_config,
|
||||
renderer=self.renderer,
|
||||
chat_template_config=self.chat_template_config,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Override upstream _preprocess_cmpl so that omni-specific fields
|
||||
# (additional_information, prompt_embeds, …) survive the renderer's
|
||||
# process_for_engine step which only copies standard vLLM keys.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _preprocess_cmpl(
|
||||
self,
|
||||
prompts: Sequence[PromptType],
|
||||
tokenization_kwargs: dict[str, Any] | None = None,
|
||||
) -> Sequence[ProcessorInputs]:
|
||||
renderer = self.renderer
|
||||
model_config = self.model_config
|
||||
|
||||
parsed_prompts = [parse_model_prompt(model_config, prompt) for prompt in prompts]
|
||||
tok_params = renderer.default_cmpl_tok_params.with_kwargs(**(tokenization_kwargs or {}))
|
||||
results = renderer.render_cmpl(parsed_prompts, tok_params)
|
||||
|
||||
reinject_omni_fields(results, parsed_prompts)
|
||||
return results
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close resources.
|
||||
|
||||
Note: Stage management is now handled by Omni class.
|
||||
This method closes the LLM engine but not stages.
|
||||
"""
|
||||
# Close the LLM engine if it exists
|
||||
if hasattr(self, "llm_engine") and self.llm_engine is not None:
|
||||
if hasattr(self.llm_engine, "shutdown"):
|
||||
self.llm_engine.shutdown()
|
||||
|
||||
def __del__(self) -> None: # best-effort
|
||||
try:
|
||||
self.close()
|
||||
except Exception as e:
|
||||
logger.debug("[Orchestrator] __del__ close() raised: %s", e, exc_info=True)
|
||||
|
||||
def _run_engine(
|
||||
self, output_type=None, *, use_tqdm: bool | Callable[..., tqdm] = True
|
||||
) -> list[RequestOutput | PoolingRequestOutput]:
|
||||
# Initialize tqdm.
|
||||
if use_tqdm:
|
||||
num_requests = self.llm_engine.get_num_unfinished_requests()
|
||||
tqdm_func = use_tqdm if callable(use_tqdm) else tqdm
|
||||
pbar = tqdm_func(
|
||||
total=num_requests,
|
||||
desc="Processed prompts",
|
||||
dynamic_ncols=True,
|
||||
postfix=(f"est. speed input: {0:.2f} toks/s, output: {0:.2f} toks/s"),
|
||||
)
|
||||
|
||||
# Run the engine.
|
||||
outputs: list[RequestOutput | PoolingRequestOutput] = []
|
||||
total_in_toks = 0
|
||||
total_out_toks = 0
|
||||
while self.llm_engine.has_unfinished_requests():
|
||||
step_outputs = self.llm_engine.step()
|
||||
for output in step_outputs:
|
||||
if output.finished:
|
||||
outputs.append(output)
|
||||
if use_tqdm:
|
||||
if isinstance(output, RequestOutput):
|
||||
# Calculate tokens only for RequestOutput
|
||||
n = len(output.outputs)
|
||||
assert output.prompt_token_ids is not None
|
||||
total_in_toks += len(output.prompt_token_ids) * n
|
||||
in_spd = total_in_toks / pbar.format_dict["elapsed"]
|
||||
total_out_toks += sum(len(stp.token_ids) for stp in output.outputs)
|
||||
out_spd = total_out_toks / pbar.format_dict["elapsed"]
|
||||
pbar.postfix = f"est. speed input: {in_spd:.2f} toks/s, output: {out_spd:.2f} toks/s"
|
||||
pbar.update(n)
|
||||
else:
|
||||
pbar.update(1)
|
||||
if pbar.n == num_requests:
|
||||
pbar.refresh()
|
||||
|
||||
if use_tqdm:
|
||||
pbar.close()
|
||||
# Sort the outputs by the int part of request ID which is in format of 'int-uuid'.
|
||||
# This is necessary because some requests may be finished earlier than
|
||||
# its previous requests.
|
||||
return sorted(outputs, key=lambda x: int(x.request_id.split("-")[0]))
|
||||
File diff suppressed because it is too large.
Load diff
@@ -111,10 +111,9 @@ from vllm_omni.entrypoints.openai.serving_speech_stream import OmniStreamingSpee
|
||||
from vllm_omni.entrypoints.openai.serving_video import OmniOpenAIServingVideo, ReferenceImage
|
||||
from vllm_omni.entrypoints.openai.storage import STORAGE_MANAGER
|
||||
from vllm_omni.entrypoints.openai.stores import VIDEO_STORE, VIDEO_TASKS
|
||||
from vllm_omni.entrypoints.openai.utils import get_stage_type, parse_lora_request
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import decode_input_reference
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParams, OmniTextPrompt
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.lora.utils import stable_lora_int_id
|
||||
|
||||
logger = init_logger(__name__)
|
||||
router = APIRouter()
|
||||
@@ -163,6 +162,12 @@ def _remove_route_from_router(
|
||||
ENDPOINT_LOAD_METRICS_FORMAT_HEADER_LABEL = "endpoint-load-metrics-format"
|
||||
|
||||
|
||||
async def _get_vllm_config(engine_client: EngineClient) -> Any:
|
||||
if hasattr(engine_client, "get_vllm_config"):
|
||||
return await engine_client.get_vllm_config()
|
||||
return getattr(engine_client, "vllm_config", None)
|
||||
|
||||
|
||||
def _remove_route_from_app(app, path: str, methods: set[str] | None = None):
|
||||
"""Remove a route from the app by path and optionally by methods.
|
||||
|
||||
@@ -187,13 +192,31 @@ class _DiffusionServingModels:
|
||||
provide a lightweight fallback.
|
||||
"""
|
||||
|
||||
class _NullModelConfig:
|
||||
def __getattr__(self, name):
|
||||
return None
|
||||
|
||||
class _Unsupported:
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
raise NotImplementedError(f"{self.name} is not supported in diffusion mode")
|
||||
|
||||
def __getattr__(self, attr):
|
||||
raise NotImplementedError(f"{self.name}.{attr} is not supported in diffusion mode")
|
||||
|
||||
def __init__(self, base_model_paths: list[BaseModelPath]) -> None:
|
||||
self._base_model_paths = base_model_paths
|
||||
self.model_config = self._NullModelConfig()
|
||||
|
||||
@property
|
||||
def base_model_paths(self) -> list[BaseModelPath]:
|
||||
return self._base_model_paths
|
||||
|
||||
def __getattr__(self, name):
|
||||
return self._Unsupported(name)
|
||||
|
||||
async def show_available_models(self) -> ModelList:
|
||||
return ModelList(
|
||||
data=[
|
||||
@@ -276,7 +299,7 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
|
||||
logger.warning("Profiler endpoints are enabled. This should ONLY be used for local development!")
|
||||
app.include_router(profiler_router)
|
||||
|
||||
vllm_config = await engine_client.get_vllm_config()
|
||||
vllm_config = await _get_vllm_config(engine_client)
|
||||
|
||||
# Check if pure diffusion mode (vllm_config will be None)
|
||||
is_pure_diffusion = vllm_config is None
|
||||
@@ -334,7 +357,7 @@ async def build_async_omni(
|
||||
Args:
|
||||
args: Parsed command-line arguments containing model and configuration
|
||||
disable_frontend_multiprocessing: Optional flag to disable frontend
|
||||
multiprocessing (deprecated in V1)
|
||||
multiprocessing
|
||||
client_config: Optional client configuration dictionary
|
||||
|
||||
Yields:
|
||||
@@ -372,7 +395,7 @@ async def build_async_omni_from_stage_config(
|
||||
Args:
|
||||
args: Parsed command-line arguments containing model and stage configs
|
||||
disable_frontend_multiprocessing: Flag to disable frontend multiprocessing
|
||||
(deprecated in V1)
|
||||
for compatibility with existing CLI options
|
||||
client_config: Optional client configuration dictionary
|
||||
|
||||
Yields:
|
||||
@@ -383,16 +406,13 @@ async def build_async_omni_from_stage_config(
|
||||
otherwise from the model's default configuration.
|
||||
"""
|
||||
|
||||
# V1 AsyncLLM.
|
||||
if disable_frontend_multiprocessing:
|
||||
logger.warning("V1 is enabled, but got --disable-frontend-multiprocessing.")
|
||||
logger.warning("Ignoring --disable-frontend-multiprocessing for AsyncOmni runtime.")
|
||||
|
||||
async_omni: EngineClient | None = None
|
||||
|
||||
try:
|
||||
# Convert args Namespace to kwargs dict for AsyncOmni to use
|
||||
kwargs = vars(args).copy()
|
||||
# Remove model as it will be passed separately
|
||||
kwargs.pop("model", None)
|
||||
async_omni = AsyncOmni(model=args.model, **kwargs)
|
||||
|
||||
@@ -423,14 +443,14 @@ async def omni_init_app_state(
|
||||
args: Parsed command-line arguments
|
||||
"""
|
||||
# Get vllm_config from engine_client (following 0.14.0 pattern)
|
||||
vllm_config = await engine_client.get_vllm_config()
|
||||
vllm_config = await _get_vllm_config(engine_client)
|
||||
|
||||
# Detect if it's pure Diffusion mode (single stage and is Diffusion)
|
||||
is_pure_diffusion = False
|
||||
if hasattr(engine_client, "stage_configs") and engine_client.stage_configs:
|
||||
stage_configs = engine_client.stage_configs
|
||||
if len(stage_configs) == 1:
|
||||
stage_type = stage_configs[0].get("stage_type", "llm")
|
||||
stage_type = get_stage_type(stage_configs[0])
|
||||
if stage_type == "diffusion":
|
||||
is_pure_diffusion = True
|
||||
logger.info("Detected pure diffusion mode (single diffusion stage)")
|
||||
@@ -483,7 +503,7 @@ async def omni_init_app_state(
|
||||
# LLM or multi-stage mode: use standard initialization logic
|
||||
if vllm_config is None:
|
||||
# Try to get vllm_config from engine_client
|
||||
vllm_config = await engine_client.get_vllm_config()
|
||||
vllm_config = await _get_vllm_config(engine_client)
|
||||
if vllm_config is None:
|
||||
logger.warning("vllm_config is None, some features may not work correctly")
|
||||
|
||||
@@ -528,15 +548,13 @@ async def omni_init_app_state(
|
||||
# Try to initialize processors if vllm_config is available
|
||||
try:
|
||||
from vllm.plugins.io_processors import get_io_processor
|
||||
|
||||
from vllm_omni.engine.input_processor import OmniInputProcessor
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
|
||||
tokenizer = await engine_client.get_tokenizer()
|
||||
if tokenizer is not None:
|
||||
# Initialize input_processor
|
||||
# OMNI: OmniInputProcessor creates tokenizer internally from vllm_config
|
||||
if not hasattr(engine_client, "input_processor") or engine_client.input_processor is None:
|
||||
engine_client.input_processor = OmniInputProcessor(
|
||||
engine_client.input_processor = InputProcessor(
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
logger.info("Initialized input_processor for AsyncOmni")
|
||||
@@ -1167,7 +1185,7 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
HTTPException: For validation errors, missing engine, or generation failures
|
||||
"""
|
||||
# Get engine client (AsyncOmni) from app state
|
||||
engine_client, model_name, stage_types = _get_engine_and_model(raw_request)
|
||||
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
|
||||
|
||||
# Validate model field (warn if mismatch, don't error)
|
||||
if request.model is not None and request.model != model_name:
|
||||
@@ -1219,7 +1237,7 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
|
||||
result = await _generate_with_async_omni(
|
||||
engine_client=engine_client,
|
||||
gen_params=gen_params,
|
||||
stage_types=stage_types,
|
||||
stage_configs=stage_configs,
|
||||
prompt=prompt,
|
||||
request_id=request_id,
|
||||
)
|
||||
@@ -1294,7 +1312,7 @@ async def edit_images(
|
||||
OpenAI-compatible image edit endpoint.
|
||||
"""
|
||||
# 1. get engine and model
|
||||
engine_client, model_name, stage_types = _get_engine_and_model(raw_request)
|
||||
engine_client, model_name, stage_configs = _get_engine_and_model(raw_request)
|
||||
if model is not None and model != model_name:
|
||||
logger.warning(
|
||||
f"Model mismatch: request specifies '{model}' but server is running '{model_name}'. Using server model."
|
||||
@@ -1329,8 +1347,14 @@ async def edit_images(
|
||||
# 3.0 Init with system default values
|
||||
app_state_args = getattr(raw_request.app.state, "args", None)
|
||||
default_sample_param = getattr(app_state_args, "default_sampling_params", None)
|
||||
# Currently only have one diffusion stage
|
||||
diffusion_stage_id = [i for i, t in enumerate(stage_types) if t == "diffusion"][0]
|
||||
# Currently only have one diffusion stage.
|
||||
diffusion_stage_ids = [i for i, cfg in enumerate(stage_configs) if get_stage_type(cfg) == "diffusion"]
|
||||
if not diffusion_stage_ids:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="No diffusion stage found in multi-stage pipeline.",
|
||||
)
|
||||
diffusion_stage_id = diffusion_stage_ids[0]
|
||||
apply_stage_default_sampling_params(
|
||||
default_sample_param,
|
||||
gen_params,
|
||||
@@ -1377,7 +1401,7 @@ async def edit_images(
|
||||
result = await _generate_with_async_omni(
|
||||
engine_client=engine_client,
|
||||
gen_params=gen_params,
|
||||
stage_types=stage_types,
|
||||
stage_configs=stage_configs,
|
||||
prompt=prompt,
|
||||
request_id=request_id,
|
||||
)
|
||||
@@ -1418,42 +1442,26 @@ async def edit_images(
|
||||
def _get_engine_and_model(raw_request: Request):
|
||||
# Get engine client (AsyncOmni) from app state
|
||||
engine_client: EngineClient | AsyncOmni | None = getattr(raw_request.app.state, "engine_client", None)
|
||||
if engine_client is None or not hasattr(engine_client, "stage_list"):
|
||||
if engine_client is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="Multi-stage engine not initialized. Start server with a multi-stage omni model.",
|
||||
)
|
||||
|
||||
# Check if there's a diffusion stage
|
||||
# Check if there's a diffusion stage.
|
||||
# Prefer app state (compat layer populated at startup), then fall back to
|
||||
# the engine client's stage configs for refactored AsyncOmni paths.
|
||||
stage_configs = getattr(raw_request.app.state, "stage_configs", None)
|
||||
if not stage_configs:
|
||||
stage_configs = getattr(engine_client, "stage_configs", None)
|
||||
if not stage_configs:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="Stage configs not found. Start server with a multi-stage omni model.",
|
||||
)
|
||||
|
||||
# Check for diffusion stage and collect stage types
|
||||
has_diffusion_stage = False
|
||||
stage_types: list[str] = []
|
||||
for stage in stage_configs:
|
||||
# Handle both dict and OmegaConf objects
|
||||
stage_type = None
|
||||
if isinstance(stage, dict):
|
||||
stage_type = stage.get("stage_type", "llm")
|
||||
elif hasattr(stage, "get"):
|
||||
stage_type = stage.get("stage_type", "llm")
|
||||
elif hasattr(stage, "stage_type"):
|
||||
stage_type = stage.stage_type
|
||||
else:
|
||||
# Fallback: try to access as dict-like
|
||||
try:
|
||||
stage_type = stage["stage_type"] if "stage_type" in stage else "llm"
|
||||
except (TypeError, KeyError):
|
||||
stage_type = "llm"
|
||||
|
||||
if stage_type == "diffusion":
|
||||
has_diffusion_stage = True
|
||||
stage_types.append(stage_type)
|
||||
normalized_stage_configs = list(stage_configs)
|
||||
has_diffusion_stage = any(get_stage_type(stage_cfg) == "diffusion" for stage_cfg in normalized_stage_configs)
|
||||
|
||||
if not has_diffusion_stage:
|
||||
raise HTTPException(
|
||||
@@ -1463,12 +1471,13 @@ def _get_engine_and_model(raw_request: Request):
|
||||
|
||||
# Get server's loaded model name
|
||||
serving_models = getattr(raw_request.app.state, "openai_serving_models", None)
|
||||
if serving_models and hasattr(serving_models, "base_model_paths") and serving_models.base_model_paths:
|
||||
model_name = serving_models.base_model_paths[0].name
|
||||
base_model_paths = getattr(serving_models, "base_model_paths", None) if serving_models else None
|
||||
if base_model_paths:
|
||||
model_name = base_model_paths[0].name
|
||||
else:
|
||||
model_name = "unknown"
|
||||
|
||||
return engine_client, model_name, stage_types
|
||||
return engine_client, model_name, normalized_stage_configs
|
||||
|
||||
|
||||
def _get_lora_from_json_str(lora_body):
|
||||
@@ -1486,81 +1495,63 @@ def _get_lora_from_json_str(lora_body):
|
||||
|
||||
|
||||
def _parse_lora_request(lora_body: dict[str, Any]):
|
||||
if lora_body is not None:
|
||||
if not isinstance(lora_body, dict):
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="Invalid lora field: expected an object.",
|
||||
)
|
||||
lora_name = lora_body.get("name") or lora_body.get("lora_name") or lora_body.get("adapter")
|
||||
lora_path = (
|
||||
lora_body.get("local_path")
|
||||
or lora_body.get("path")
|
||||
or lora_body.get("lora_path")
|
||||
or lora_body.get("lora_local_path")
|
||||
)
|
||||
lora_scale = lora_body.get("scale")
|
||||
if lora_scale is None:
|
||||
lora_scale = lora_body.get("lora_scale")
|
||||
lora_int_id = lora_body.get("int_id")
|
||||
if lora_int_id is None:
|
||||
lora_int_id = lora_body.get("lora_int_id")
|
||||
if lora_int_id is None and lora_path:
|
||||
lora_int_id = stable_lora_int_id(str(lora_path))
|
||||
|
||||
if not lora_name or not lora_path:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="Invalid lora object: both name and path are required.",
|
||||
)
|
||||
|
||||
return LoRARequest(str(lora_name), int(lora_int_id), str(lora_path)), lora_scale
|
||||
return None, None
|
||||
try:
|
||||
return parse_lora_request(lora_body)
|
||||
except ValueError as e:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=str(e),
|
||||
) from e
|
||||
|
||||
|
||||
async def _generate_with_async_omni(
|
||||
engine_client: AsyncOmni | Any,
|
||||
gen_params: Any,
|
||||
stage_types: list[str],
|
||||
stage_configs: list[Any],
|
||||
**kwargs,
|
||||
):
|
||||
engine_client = cast(AsyncOmni, engine_client)
|
||||
result = None
|
||||
stage_list = getattr(engine_client, "stage_list", None)
|
||||
if isinstance(stage_list, list):
|
||||
default_params_list: list[OmniSamplingParams] | None = getattr(
|
||||
engine_client, "default_sampling_params_list", None
|
||||
normalized_stage_configs = list(stage_configs)
|
||||
if not normalized_stage_configs:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="Stage configs not found. Start server with a multi-stage omni model.",
|
||||
)
|
||||
if not isinstance(default_params_list, list):
|
||||
default_params_list = [
|
||||
OmniDiffusionSamplingParams() if st == "diffusion" else SamplingParams() for st in stage_types
|
||||
]
|
||||
else:
|
||||
default_params_list = list(default_params_list)
|
||||
if len(default_params_list) != len(stage_types):
|
||||
default_params_list = (
|
||||
default_params_list
|
||||
+ [OmniDiffusionSamplingParams() if st == "diffusion" else SamplingParams() for st in stage_types]
|
||||
)[: len(stage_types)]
|
||||
|
||||
sampling_params_list: list[OmniSamplingParams] = []
|
||||
for idx, stage_type in enumerate(stage_types):
|
||||
if stage_type == "diffusion":
|
||||
sampling_params_list.append(gen_params)
|
||||
else:
|
||||
base_params = default_params_list[idx]
|
||||
sampling_params_list.append(base_params)
|
||||
|
||||
async for output in engine_client.generate(
|
||||
sampling_params_list=sampling_params_list,
|
||||
**kwargs,
|
||||
):
|
||||
result = output
|
||||
default_params_list: list[OmniSamplingParams] | None = getattr(
|
||||
engine_client,
|
||||
"default_sampling_params_list",
|
||||
None,
|
||||
)
|
||||
if not isinstance(default_params_list, list):
|
||||
default_params_list = []
|
||||
else:
|
||||
result = await engine_client.generate(
|
||||
sampling_params_list=[gen_params],
|
||||
**kwargs,
|
||||
)
|
||||
default_params_list = list(default_params_list)
|
||||
|
||||
sampling_params_list: list[OmniSamplingParams] = []
|
||||
for idx, stage_cfg in enumerate(normalized_stage_configs):
|
||||
stage_type = get_stage_type(stage_cfg)
|
||||
if stage_type == "diffusion":
|
||||
sampling_params_list.append(gen_params)
|
||||
continue
|
||||
|
||||
if idx < len(default_params_list):
|
||||
default_stage_params = default_params_list[idx]
|
||||
else:
|
||||
default_stage_params = SamplingParams()
|
||||
|
||||
if hasattr(default_stage_params, "clone"):
|
||||
try:
|
||||
default_stage_params = default_stage_params.clone()
|
||||
except Exception:
|
||||
pass
|
||||
sampling_params_list.append(default_stage_params)
|
||||
|
||||
async for output in engine_client.generate(
|
||||
sampling_params_list=sampling_params_list,
|
||||
**kwargs,
|
||||
):
|
||||
result = output
|
||||
|
||||
if result is None:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -84,8 +84,8 @@ from vllm.utils.collection_utils import as_list
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
|
||||
from vllm_omni.entrypoints.openai.protocol import OmniChatCompletionStreamResponse
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import AudioResponse, CreateAudio
|
||||
from vllm_omni.entrypoints.openai.utils import parse_lora_request
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.lora.utils import stable_lora_int_id
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -326,6 +326,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
tprompt: OmniTextPrompt = {"prompt": extracted_prompt}
|
||||
if is_img2img:
|
||||
tprompt["modalities"] = ["img2img"]
|
||||
else:
|
||||
tprompt["modalities"] = ["image"]
|
||||
if negative_prompt is not None:
|
||||
tprompt["negative_prompt"] = negative_prompt
|
||||
# GLM-Image's _call_hf_processor expects target_h/target_w in mm_processor_kwargs
|
||||
@@ -626,10 +628,10 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
return final_sampling_params_list
|
||||
|
||||
def _get_comprehension_stage_index(self) -> int:
|
||||
for idx, stage in enumerate(self.engine_client.stage_list):
|
||||
for idx, stage in enumerate(self.engine_client.stage_configs):
|
||||
if stage.is_comprehension:
|
||||
return idx
|
||||
raise ValueError("No comprehension stage (is_comprehension=True) found in stage_list")
|
||||
raise ValueError("No comprehension stage (is_comprehension=True) found in stage configs")
|
||||
|
||||
# OpenAI API standard sampling parameters that can be safely overridden.
|
||||
# These are the most commonly used parameters with compatible types
|
||||
@@ -2104,27 +2106,11 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# Parse per-request LoRA (works for both AsyncOmniDiffusion and AsyncOmni).
|
||||
if lora_body and isinstance(lora_body, dict):
|
||||
try:
|
||||
lora_name = lora_body.get("name") or lora_body.get("lora_name") or lora_body.get("adapter")
|
||||
lora_path = (
|
||||
lora_body.get("local_path")
|
||||
or lora_body.get("path")
|
||||
or lora_body.get("lora_path")
|
||||
or lora_body.get("lora_local_path")
|
||||
)
|
||||
# using "or" directly here may be buggy if `scale=0`
|
||||
lora_scale = lora_body.get("scale")
|
||||
if lora_scale is None:
|
||||
lora_scale = lora_body.get("lora_scale")
|
||||
lora_int_id = lora_body.get("int_id")
|
||||
if lora_int_id is None:
|
||||
lora_int_id = lora_body.get("lora_int_id")
|
||||
if lora_int_id is None and lora_path:
|
||||
lora_int_id = stable_lora_int_id(str(lora_path))
|
||||
if lora_name and lora_path:
|
||||
lora_req = LoRARequest(str(lora_name), int(lora_int_id), str(lora_path))
|
||||
lora_req, lora_scale = parse_lora_request(lora_body)
|
||||
if lora_req is not None:
|
||||
gen_params.lora_request = lora_req
|
||||
if lora_scale is not None:
|
||||
gen_params.lora_scale = float(lora_scale)
|
||||
gen_params.lora_scale = lora_scale
|
||||
except Exception as e: # pragma: no cover - safeguard
|
||||
logger.warning("Failed to parse LoRA request: %s", e)
|
||||
|
||||
@@ -2152,8 +2138,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
|
||||
# Generate image
|
||||
# Handle both AsyncOmniDiffusion (returns OmniRequestOutput) and AsyncOmni (returns AsyncGenerator)
|
||||
if hasattr(self._diffusion_engine, "stage_list"):
|
||||
# AsyncOmni: iterate through async generator to get final output
|
||||
if isinstance(self._diffusion_engine, AsyncOmni):
|
||||
diffusion_engine = cast(AsyncOmni, self._diffusion_engine)
|
||||
result = None
|
||||
async for output in diffusion_engine.generate(
|
||||
|
||||
@@ -197,12 +197,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
return None
|
||||
|
||||
def _find_tts_stage(self):
|
||||
"""Find and return the TTS stage from the stage list, or None if not found."""
|
||||
stage_list = getattr(self.engine_client, "stage_list", None)
|
||||
if stage_list is None:
|
||||
return None
|
||||
for stage in stage_list:
|
||||
if getattr(stage, "model_stage", None) in _TTS_MODEL_STAGES:
|
||||
"""Find and return the TTS stage config, or None if not found."""
|
||||
for stage in self.engine_client.stage_configs:
|
||||
if stage.engine_args.model_stage in _TTS_MODEL_STAGES:
|
||||
return stage
|
||||
return None
|
||||
|
||||
@@ -496,13 +493,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
|
||||
def _is_tts_model(self) -> bool:
|
||||
"""Check if the current model is a supported TTS model."""
|
||||
stage_list = getattr(self.engine_client, "stage_list", None)
|
||||
if stage_list:
|
||||
for stage in stage_list:
|
||||
model_stage = getattr(stage, "model_stage", None)
|
||||
if model_stage in _TTS_MODEL_STAGES:
|
||||
return True
|
||||
return False
|
||||
return any(stage.engine_args.model_stage in _TTS_MODEL_STAGES for stage in self.engine_client.stage_configs)
|
||||
|
||||
def _validate_tts_request(self, request: OpenAICreateSpeechRequest) -> str | None:
|
||||
"""Validate TTS request parameters. Returns error message or None."""
|
||||
|
||||
@@ -19,10 +19,9 @@ from vllm_omni.entrypoints.openai.protocol.videos import (
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationResponse,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.utils import get_stage_type, parse_lora_request
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import encode_video_base64
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParams, OmniTextPrompt
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.lora.utils import stable_lora_int_id
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -161,38 +160,20 @@ class OmniOpenAIServingVideo:
|
||||
|
||||
@staticmethod
|
||||
def _apply_lora(lora_body: Any, gen_params: OmniDiffusionSamplingParams) -> None:
|
||||
if lora_body is None:
|
||||
try:
|
||||
lora_request, lora_scale = parse_lora_request(lora_body)
|
||||
except ValueError as e:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail=str(e),
|
||||
) from e
|
||||
|
||||
if lora_request is None:
|
||||
return
|
||||
if not isinstance(lora_body, dict):
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="Invalid lora field: expected an object.",
|
||||
)
|
||||
lora_name = lora_body.get("name") or lora_body.get("lora_name") or lora_body.get("adapter")
|
||||
lora_path = (
|
||||
lora_body.get("local_path")
|
||||
or lora_body.get("path")
|
||||
or lora_body.get("lora_path")
|
||||
or lora_body.get("lora_local_path")
|
||||
)
|
||||
lora_scale = lora_body.get("scale")
|
||||
if lora_scale is None:
|
||||
lora_scale = lora_body.get("lora_scale")
|
||||
lora_int_id = lora_body.get("int_id")
|
||||
if lora_int_id is None:
|
||||
lora_int_id = lora_body.get("lora_int_id")
|
||||
if lora_int_id is None and lora_path:
|
||||
lora_int_id = stable_lora_int_id(str(lora_path))
|
||||
|
||||
if not lora_name or not lora_path:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="Invalid lora object: both name and path are required.",
|
||||
)
|
||||
|
||||
gen_params.lora_request = LoRARequest(str(lora_name), int(lora_int_id), str(lora_path))
|
||||
gen_params.lora_request = lora_request
|
||||
if lora_scale is not None:
|
||||
gen_params.lora_scale = float(lora_scale)
|
||||
gen_params.lora_scale = lora_scale
|
||||
|
||||
async def _run_generation(
|
||||
self,
|
||||
@@ -200,44 +181,26 @@ class OmniOpenAIServingVideo:
|
||||
gen_params: OmniDiffusionSamplingParams,
|
||||
request_id: str,
|
||||
) -> Any:
|
||||
has_stage_list = hasattr(self._engine_client, "stage_list")
|
||||
logger.info(
|
||||
"Video generation routing: stage_configs=%s, has_stage_list=%s, engine_type=%s",
|
||||
"present" if self._stage_configs else "missing",
|
||||
has_stage_list,
|
||||
type(self._engine_client).__name__,
|
||||
)
|
||||
stage_configs = self._stage_configs or getattr(self._engine_client, "stage_configs", None)
|
||||
|
||||
if not stage_configs:
|
||||
if not hasattr(self._engine_client, "stage_list"):
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="Stage configs not found. Start server with an omni diffusion model.",
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail="Stage configs not found. Start server with an omni diffusion model.",
|
||||
)
|
||||
|
||||
# Video generation endpoint only supports diffusion stages.
|
||||
if stage_configs:
|
||||
for stage in stage_configs:
|
||||
# Extract stage_type: dicts and OmegaConf objects use .get(), others use getattr
|
||||
if hasattr(stage, "get"):
|
||||
stage_type = stage.get("stage_type", "llm")
|
||||
else:
|
||||
stage_type = getattr(stage, "stage_type", "llm")
|
||||
|
||||
if stage_type != "diffusion":
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail=f"Video generation only supports diffusion stages, found '{stage_type}' stage.",
|
||||
)
|
||||
for stage in stage_configs:
|
||||
stage_type = get_stage_type(stage)
|
||||
if stage_type != "diffusion":
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
detail=f"Video generation only supports diffusion stages, found '{stage_type}' stage.",
|
||||
)
|
||||
|
||||
# Common generation logic for both paths
|
||||
engine_client = cast(AsyncOmni, self._engine_client)
|
||||
stage_list = getattr(engine_client, "stage_list", None)
|
||||
if isinstance(stage_list, list):
|
||||
sampling_params_list: list[OmniSamplingParams] = [gen_params for _ in stage_list]
|
||||
else:
|
||||
sampling_params_list = [gen_params]
|
||||
sampling_params_list: list[OmniSamplingParams] = [gen_params for _ in stage_configs]
|
||||
|
||||
result = None
|
||||
async for output in engine_client.generate(
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.lora.utils import stable_lora_int_id
|
||||
|
||||
|
||||
def get_stage_type(stage_cfg: Any) -> str:
|
||||
"""Best-effort stage type resolver across dict/omegaconf/object configs."""
|
||||
if isinstance(stage_cfg, dict):
|
||||
return stage_cfg.get("stage_type", "llm")
|
||||
if hasattr(stage_cfg, "get"):
|
||||
try:
|
||||
return stage_cfg.get("stage_type", "llm")
|
||||
except Exception:
|
||||
pass
|
||||
return getattr(stage_cfg, "stage_type", "llm")
|
||||
|
||||
|
||||
def parse_lora_request(lora_body: Any) -> tuple[LoRARequest | None, float | None]:
|
||||
"""Parse a request-level LoRA object into a LoRARequest and optional scale.
|
||||
|
||||
Raises:
|
||||
ValueError: If the object shape is invalid or required fields are missing.
|
||||
"""
|
||||
if lora_body is None:
|
||||
return None, None
|
||||
|
||||
if not isinstance(lora_body, dict):
|
||||
raise ValueError("Invalid lora field: expected an object.")
|
||||
|
||||
lora_name = lora_body.get("name") or lora_body.get("lora_name") or lora_body.get("adapter")
|
||||
lora_path = (
|
||||
lora_body.get("local_path")
|
||||
or lora_body.get("path")
|
||||
or lora_body.get("lora_path")
|
||||
or lora_body.get("lora_local_path")
|
||||
)
|
||||
lora_scale = lora_body.get("scale")
|
||||
if lora_scale is None:
|
||||
lora_scale = lora_body.get("lora_scale")
|
||||
lora_int_id = lora_body.get("int_id")
|
||||
if lora_int_id is None:
|
||||
lora_int_id = lora_body.get("lora_int_id")
|
||||
if lora_int_id is None and lora_path:
|
||||
lora_int_id = stable_lora_int_id(str(lora_path))
|
||||
|
||||
if not lora_name or not lora_path:
|
||||
raise ValueError("Invalid lora object: both name and path are required.")
|
||||
|
||||
scale = float(lora_scale) if lora_scale is not None else None
|
||||
return LoRARequest(str(lora_name), int(lora_int_id), str(lora_path)), scale
|
||||
@@ -1,11 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import importlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from multiprocessing import shared_memory as _shm
|
||||
from typing import Any
|
||||
|
||||
@@ -14,38 +10,6 @@ from vllm_omni.config.yaml_util import to_dict as _omega_to_dict
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def load_func_from_config(func_path: str | None) -> Callable[..., Any] | None:
|
||||
"""Dynamically import a callable from a fully-qualified dotted path.
|
||||
|
||||
Args:
|
||||
func_path: Dotted path such as ``"pkg.module.func_name"``, or *None*.
|
||||
|
||||
Returns:
|
||||
The imported callable, or *None* when *func_path* is falsy.
|
||||
"""
|
||||
if not func_path:
|
||||
return None
|
||||
module_path, func_name = func_path.rsplit(".", 1)
|
||||
module = importlib.import_module(module_path)
|
||||
return getattr(module, func_name)
|
||||
|
||||
|
||||
class OmniStageTaskType(enum.Enum):
|
||||
GENERATE = "generate"
|
||||
ABORT = "abort"
|
||||
SHUTDOWN = "shutdown"
|
||||
PROFILER_START = "profiler_start"
|
||||
PROFILER_STOP = "profiler_stop"
|
||||
COLLECTIVE_RPC = "collective_rpc"
|
||||
|
||||
|
||||
SHUTDOWN_TASK = {"type": OmniStageTaskType.SHUTDOWN}
|
||||
|
||||
|
||||
def is_profiler_task(task_type: OmniStageTaskType) -> bool:
|
||||
return task_type in (OmniStageTaskType.PROFILER_START, OmniStageTaskType.PROFILER_STOP)
|
||||
|
||||
|
||||
def set_stage_devices(
|
||||
stage_id: int,
|
||||
devices: str | int | None,
|
||||
@@ -207,58 +171,6 @@ def shm_read_bytes(meta: dict[str, Any]) -> bytes:
|
||||
return data
|
||||
|
||||
|
||||
def _ensure_parent_dir(path: str) -> None:
|
||||
"""Ensure the parent directory for a file path exists (best-effort)."""
|
||||
try:
|
||||
parent = os.path.dirname(path)
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def append_jsonl(path: str, record: dict[str, Any]) -> None:
|
||||
"""Append a JSON record as one line to a JSONL file (best-effort).
|
||||
|
||||
This is safe to call from multiple processes when each process writes
|
||||
to a distinct file. For concurrent writes to the same file, OS append
|
||||
semantics typically suffice, but no additional locking is provided.
|
||||
"""
|
||||
try:
|
||||
_ensure_parent_dir(path)
|
||||
line = json.dumps(record, ensure_ascii=False)
|
||||
fd = os.open(path, os.O_APPEND | os.O_CREAT | os.O_WRONLY, 0o644)
|
||||
with os.fdopen(fd, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
except Exception:
|
||||
logger.exception("Failed to append JSONL to %s", path)
|
||||
|
||||
|
||||
def maybe_dump_to_shm(obj: Any, threshold: int) -> tuple[bool, Any]:
|
||||
"""Dump object to SHM if serialized size exceeds threshold.
|
||||
|
||||
Returns (True, meta) when dumped; otherwise (False, original_obj).
|
||||
"""
|
||||
payload = serialize_obj(obj)
|
||||
if len(payload) > threshold:
|
||||
logger.debug(f"Dumping object to SHM with size: {len(payload)}")
|
||||
return True, shm_write_bytes(payload, name=None)
|
||||
return False, obj
|
||||
|
||||
|
||||
def maybe_load_from_ipc(container: dict[str, Any], obj_key: str, shm_key: str) -> Any:
|
||||
"""Load object from container that may carry SHM or inline object.
|
||||
|
||||
Deprecated: prefer `maybe_load_from_ipc_with_metrics` to also obtain
|
||||
decode-time and size metrics.
|
||||
"""
|
||||
if shm_key in container:
|
||||
from vllm_omni.distributed.omni_connectors.utils.serialization import OmniSerializer
|
||||
|
||||
return OmniSerializer.deserialize(shm_read_bytes(container[shm_key]))
|
||||
return container[obj_key]
|
||||
|
||||
|
||||
def maybe_load_from_ipc_with_metrics(
|
||||
container: dict[str, Any], obj_key: str, shm_key: str
|
||||
) -> tuple[Any, dict[str, float]]:
|
||||
@@ -295,21 +207,6 @@ def maybe_load_from_ipc_with_metrics(
|
||||
}
|
||||
|
||||
|
||||
def encode_for_ipc(obj: Any, threshold: int, obj_key: str, shm_key: str) -> dict[str, Any]:
|
||||
"""Return a dict payload for IPC: inline (obj_key) or SHM (shm_key).
|
||||
|
||||
When serialized size exceeds threshold, returns {shm_key: {name,size}};
|
||||
otherwise returns {obj_key: obj}.
|
||||
"""
|
||||
payload: dict[str, Any] = {}
|
||||
use_shm, data = maybe_dump_to_shm(obj, threshold)
|
||||
if use_shm:
|
||||
payload[shm_key] = data
|
||||
else:
|
||||
payload[obj_key] = data
|
||||
return payload
|
||||
|
||||
|
||||
# Convert OmegaConf/objects to plain dicts
|
||||
def _to_dict(x: Any) -> dict[str, Any]:
|
||||
try:
|
||||
@@ -321,58 +218,3 @@ def _to_dict(x: Any) -> dict[str, Any]:
|
||||
return dict(x)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_model_to_local_path(model: str) -> str:
|
||||
"""Resolve an HF Hub model ID to its local cache snapshot path."""
|
||||
if os.path.isdir(model):
|
||||
return model
|
||||
|
||||
try:
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
# no network access is attempted, check local model path only
|
||||
return snapshot_download(model, local_files_only=True)
|
||||
except Exception:
|
||||
logger.warning(f"Could not resolve {model} to a local snapshot path; using as-is", exc_info=True)
|
||||
return model
|
||||
|
||||
|
||||
def _resolve_model_tokenizer_paths(
|
||||
model: str,
|
||||
engine_args: dict,
|
||||
) -> str:
|
||||
"""Resolve model and tokenizer paths for non-standard directory structures.
|
||||
|
||||
Some models (e.g., GLM-Image) have tokenizer in root and model in subdirectory.
|
||||
This function handles model_subdir and tokenizer_subdir engine_args.
|
||||
|
||||
When the base model path is an HF Hub ID rather than an absolute local path,
|
||||
the ID is first resolved to the local snapshot directory so that subdirectory
|
||||
joins produce valid filesystem paths.
|
||||
|
||||
Args:
|
||||
model: Base model path or HF Hub model ID
|
||||
engine_args: Engine arguments (modified in-place to remove subdir args
|
||||
and set tokenizer if needed)
|
||||
|
||||
Returns:
|
||||
Resolved model path (may be subdirectory of original)
|
||||
"""
|
||||
model_subdir = engine_args.pop("model_subdir", None)
|
||||
tokenizer_subdir = engine_args.pop("tokenizer_subdir", None)
|
||||
resolved_base = _resolve_model_to_local_path(model)
|
||||
|
||||
if model_subdir:
|
||||
model = os.path.join(resolved_base, model_subdir)
|
||||
logger.info(f"Using model subdirectory: {model}")
|
||||
|
||||
if tokenizer_subdir is not None:
|
||||
tokenizer_path = os.path.join(resolved_base, tokenizer_subdir) if tokenizer_subdir else resolved_base
|
||||
engine_args["tokenizer"] = tokenizer_path
|
||||
logger.info(f"Using tokenizer from: {tokenizer_path}")
|
||||
elif model_subdir and "tokenizer" not in engine_args:
|
||||
engine_args["tokenizer"] = resolved_base
|
||||
logger.info(f"Using tokenizer from base model path: {resolved_base}")
|
||||
|
||||
return model
|
||||
@@ -1,95 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""ZMQ-based queue utilities for Omni IPC."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
from typing import Any
|
||||
|
||||
import zmq
|
||||
from vllm.utils.network_utils import make_zmq_socket
|
||||
|
||||
|
||||
class ZmqQueue:
|
||||
"""Queue-like wrapper on a ZMQ socket."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ctx: zmq.Context,
|
||||
socket_type: int,
|
||||
*,
|
||||
bind: str | None = None,
|
||||
connect: str | None = None,
|
||||
recv_timeout_ms: int | None = None,
|
||||
send_timeout_ms: int | None = None,
|
||||
) -> None:
|
||||
# Determine path and bind mode
|
||||
path = bind if bind is not None else connect
|
||||
if path is None:
|
||||
raise ValueError("Either bind or connect must be specified")
|
||||
bind_mode = bind is not None
|
||||
|
||||
self._socket = make_zmq_socket(ctx, path, socket_type, bind=bind_mode, linger=5000)
|
||||
|
||||
# Reusable poller for efficient polling operations
|
||||
self._poller = zmq.Poller()
|
||||
self._poller.register(self._socket, zmq.POLLIN)
|
||||
|
||||
# Store default timeout settings
|
||||
self._default_recv_timeout = recv_timeout_ms
|
||||
self._default_send_timeout = send_timeout_ms
|
||||
|
||||
# Apply timeout settings if specified
|
||||
if recv_timeout_ms is not None:
|
||||
self._socket.rcvtimeo = recv_timeout_ms
|
||||
if send_timeout_ms is not None:
|
||||
self._socket.sndtimeo = send_timeout_ms
|
||||
|
||||
self.endpoint = path
|
||||
|
||||
def put(self, obj: Any) -> None:
|
||||
"""Send an object to the queue. Blocks until sent or timeout."""
|
||||
try:
|
||||
self._socket.send_pyobj(obj)
|
||||
except zmq.Again as e:
|
||||
raise queue.Full() from e
|
||||
|
||||
def put_nowait(self, obj: Any) -> None:
|
||||
"""Send an object to the queue without blocking."""
|
||||
try:
|
||||
self._socket.send_pyobj(obj, flags=zmq.NOBLOCK)
|
||||
except zmq.Again as e:
|
||||
raise queue.Full() from e
|
||||
|
||||
def get(self, timeout: float | None = None) -> Any:
|
||||
"""Receive an object from the queue with optional timeout in seconds."""
|
||||
if timeout is None:
|
||||
return self._socket.recv_pyobj()
|
||||
|
||||
# Use the reusable poller for timeout handling
|
||||
events = dict(self._poller.poll(int(timeout * 1000)))
|
||||
if events.get(self._socket) == zmq.POLLIN:
|
||||
return self._socket.recv_pyobj()
|
||||
raise queue.Empty()
|
||||
|
||||
def get_nowait(self) -> Any:
|
||||
"""Receive an object from the queue without blocking."""
|
||||
try:
|
||||
return self._socket.recv_pyobj(flags=zmq.NOBLOCK)
|
||||
except zmq.Again as e:
|
||||
raise queue.Empty() from e
|
||||
|
||||
def empty(self) -> bool:
|
||||
"""Check if the queue is empty without blocking."""
|
||||
events = dict(self._poller.poll(0))
|
||||
return events.get(self._socket) != zmq.POLLIN
|
||||
|
||||
def close(self) -> None:
|
||||
self._socket.close(0)
|
||||
|
||||
|
||||
def create_zmq_queue(ctx: zmq.Context, endpoint: str, socket_type: int) -> ZmqQueue:
|
||||
"""Create a ZmqQueue from an endpoint string and socket type."""
|
||||
return ZmqQueue(ctx, socket_type, connect=endpoint)
|
||||
Reference in new issue
Block a user