[Entrypoint][Refactor] Make field type hint more concrete (#3139)
Signed-off-by: wuhang <wuhang6@huawei.com>
This commit is contained in:
1 parent
51b4b1131e
commit
0d9d57acd9
20 files changed
+908
-543
No files matched your search
@@ -20,8 +20,8 @@ import uuid
|
||||
import weakref
|
||||
from collections.abc import Mapping, Sequence
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import asdict
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import TYPE_CHECKING, Any, Literal, cast
|
||||
|
||||
import janus
|
||||
import torch
|
||||
@@ -36,6 +36,7 @@ from vllm.v1.engine.input_processor import InputProcessor
|
||||
from vllm_omni.config.stage_config import strip_parent_engine_args
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig, parse_attention_config
|
||||
from vllm_omni.diffusion.diffusion_engine import supports_audio_output
|
||||
from vllm_omni.diffusion.inline_stage_diffusion_client import InlineStageDiffusionClient
|
||||
from vllm_omni.diffusion.stage_diffusion_client import StageDiffusionClient
|
||||
from vllm_omni.diffusion.stage_diffusion_proc import (
|
||||
complete_diffusion_handshake,
|
||||
@@ -45,11 +46,23 @@ from vllm_omni.distributed.omni_connectors.utils.initialization import (
|
||||
resolve_omni_kv_config_for_stage,
|
||||
)
|
||||
from vllm_omni.engine import OmniEngineCoreRequest
|
||||
from vllm_omni.engine.messages import (
|
||||
AbortRequestMessage,
|
||||
AddCompanionRequestMessage,
|
||||
CollectiveRPCRequestMessage,
|
||||
CollectiveRPCResultMessage,
|
||||
EngineQueueMessage,
|
||||
ErrorMessage,
|
||||
ShutdownRequestMessage,
|
||||
StageSubmissionMessage,
|
||||
)
|
||||
from vllm_omni.engine.orchestrator import Orchestrator
|
||||
from vllm_omni.engine.output_modality import FinalOutputModalityType
|
||||
from vllm_omni.engine.serialization import (
|
||||
deserialize_additional_information,
|
||||
serialize_additional_information,
|
||||
)
|
||||
from vllm_omni.engine.stage_client import StageClient
|
||||
from vllm_omni.engine.stage_engine_core_client import StageEngineCoreClientBase
|
||||
from vllm_omni.engine.stage_engine_core_proc import (
|
||||
complete_stage_handshake,
|
||||
@@ -83,12 +96,13 @@ from vllm_omni.engine.stage_init_utils import (
|
||||
setup_stage_devices,
|
||||
terminate_alive_proc,
|
||||
)
|
||||
from vllm_omni.engine.stage_pool import StagePool
|
||||
from vllm_omni.engine.stage_pool import StagePool, StagePoolClient
|
||||
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
|
||||
from vllm_omni.entrypoints.utils import (
|
||||
inject_omni_kv_config,
|
||||
load_and_resolve_stage_configs,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -99,6 +113,13 @@ logger = init_logger(__name__)
|
||||
_STARTUP_POLL_INTERVAL_S = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StageRuntimeInfo:
|
||||
final_output: bool
|
||||
final_output_type: FinalOutputModalityType | None
|
||||
stage_type: str
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Parent-EngineArgs field-routing contracts (consumed by
|
||||
# AsyncOmniEngine._strip_parent_engine_args when ``stage_configs_path`` is set).
|
||||
@@ -190,14 +211,14 @@ def _apply_omni_final_stage_metadata(
|
||||
|
||||
def _weak_shutdown_async_omni_engine(
|
||||
orchestrator_thread: threading.Thread | None,
|
||||
request_queue: janus.Queue[dict[str, Any]] | None,
|
||||
output_queue: janus.Queue[dict[str, Any]] | None,
|
||||
rpc_output_queue: janus.Queue[dict[str, Any]] | None,
|
||||
request_queue: janus.Queue[EngineQueueMessage] | None,
|
||||
output_queue: janus.Queue[EngineQueueMessage] | None,
|
||||
rpc_output_queue: janus.Queue[EngineQueueMessage] | None,
|
||||
) -> None:
|
||||
"""Best-effort orchestrator cleanup for GC finalization."""
|
||||
try:
|
||||
if request_queue is not None:
|
||||
request_queue.sync_q.put_nowait({"type": "shutdown"})
|
||||
request_queue.sync_q.put_nowait(ShutdownRequestMessage())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -295,14 +316,14 @@ class AsyncOmniEngine:
|
||||
stage0_args = getattr(self.stage_configs[0], "engine_args", None) if self.num_stages > 0 else None
|
||||
self.async_chunk = bool(getattr(stage0_args, "async_chunk", False))
|
||||
self.stage_pools: list[StagePool] = []
|
||||
self.stage_clients: list[Any] = [] # logical-stage view for external readers
|
||||
self.stage_clients: list[StageClient] = [] # logical-stage view for external readers
|
||||
self.input_processor: InputProcessor | None = None
|
||||
self.supported_tasks: tuple[str, ...] = ("generate",)
|
||||
self.default_sampling_params_list: list[Any] = []
|
||||
self.stage_metadata: list[dict[str, Any]] = []
|
||||
self.request_queue: janus.Queue[dict[str, Any]] | None = None
|
||||
self.output_queue: janus.Queue[dict[str, Any]] | None = None
|
||||
self.rpc_output_queue: janus.Queue[dict[str, Any]] | None = None
|
||||
self.default_sampling_params_list: list[OmniSamplingParams] = []
|
||||
self.stage_metadata: list[StageRuntimeInfo] = []
|
||||
self.request_queue: janus.Queue[EngineQueueMessage] | None = None
|
||||
self.output_queue: janus.Queue[EngineQueueMessage] | None = None
|
||||
self.rpc_output_queue: janus.Queue[EngineQueueMessage] | None = None
|
||||
self._shutdown_called = False
|
||||
self._weak_finalizer: weakref.finalize | None = None
|
||||
self._rpc_lock = threading.Lock()
|
||||
@@ -379,15 +400,15 @@ class AsyncOmniEngine:
|
||||
|
||||
@staticmethod
|
||||
def _collect_initialized_clients_for_cleanup(
|
||||
stage_pools: Sequence[Any],
|
||||
initialized_clients_by_stage: Mapping[int, Sequence[Any | None]],
|
||||
) -> list[Any]:
|
||||
stage_pools: Sequence[StagePool],
|
||||
initialized_clients_by_stage: Mapping[int, Sequence[StagePoolClient | None]],
|
||||
) -> list[StageClient]:
|
||||
"""Collect initialized clients exactly once for failure cleanup."""
|
||||
|
||||
collected: list[Any] = []
|
||||
collected: list[StageClient] = []
|
||||
seen: set[int] = set()
|
||||
|
||||
def _add_client(client: Any) -> None:
|
||||
def _add_client(client: StageClient | None) -> None:
|
||||
if client is None:
|
||||
return
|
||||
client_id = id(client)
|
||||
@@ -407,7 +428,7 @@ class AsyncOmniEngine:
|
||||
return collected
|
||||
|
||||
@staticmethod
|
||||
def _shutdown_initialized_clients(clients: Sequence[Any]) -> None:
|
||||
def _shutdown_initialized_clients(clients: Sequence[StageClient]) -> None:
|
||||
"""Best-effort shutdown for attached clients after init failure."""
|
||||
|
||||
for client in reversed(list(clients)):
|
||||
@@ -585,7 +606,7 @@ class AsyncOmniEngine:
|
||||
plan: ReplicaInitPlan,
|
||||
stage_init_timeout: int,
|
||||
llm_stage_launch_lock: threading.Lock,
|
||||
) -> Any:
|
||||
) -> StageEngineCoreClientBase:
|
||||
"""Initialize one LLM replica end-to-end."""
|
||||
|
||||
proc = None
|
||||
@@ -748,7 +769,7 @@ class AsyncOmniEngine:
|
||||
plan: ReplicaInitPlan,
|
||||
stage_init_timeout: int,
|
||||
stage_launch_lock: threading.Lock,
|
||||
) -> Any:
|
||||
) -> StageDiffusionClient | InlineStageDiffusionClient:
|
||||
"""Initialize one diffusion replica end-to-end."""
|
||||
|
||||
client = None
|
||||
@@ -865,7 +886,7 @@ class AsyncOmniEngine:
|
||||
plan: ReplicaInitPlan,
|
||||
stage_init_timeout: int,
|
||||
stage_launch_lock: threading.Lock,
|
||||
) -> Any:
|
||||
) -> StagePoolClient:
|
||||
"""Initialize one replica, regardless of backend type."""
|
||||
|
||||
if plan.metadata.stage_type == "diffusion":
|
||||
@@ -876,7 +897,7 @@ class AsyncOmniEngine:
|
||||
self,
|
||||
stage_plans: Sequence[LogicalStageInitPlan],
|
||||
stage_init_timeout: int,
|
||||
) -> dict[int, list[Any | None]]:
|
||||
) -> dict[int, list[StagePoolClient | None]]:
|
||||
"""Initialize all stage replicas.
|
||||
|
||||
Diffusion replicas are launched **inline on the orchestrator thread**
|
||||
@@ -892,7 +913,7 @@ class AsyncOmniEngine:
|
||||
"""
|
||||
|
||||
stage_launch_lock = threading.Lock()
|
||||
initialized_clients_by_stage: dict[int, list[Any | None]] = {
|
||||
initialized_clients_by_stage: dict[int, list[StagePoolClient | None]] = {
|
||||
plan.stage_idx: [None] * len(plan.replicas) for plan in stage_plans
|
||||
}
|
||||
primary_exc: Exception | None = None
|
||||
@@ -922,7 +943,7 @@ class AsyncOmniEngine:
|
||||
|
||||
# --- 2) LLM replicas: parallel init via a scoped ThreadPoolExecutor. ---
|
||||
if primary_exc is None and llm_replicas:
|
||||
future_to_replica: dict[concurrent.futures.Future[Any], tuple[int, int]] = {}
|
||||
future_to_replica: dict[concurrent.futures.Future[StagePoolClient], tuple[int, int]] = {}
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=max(1, len(llm_replicas)),
|
||||
thread_name_prefix="stage-init",
|
||||
@@ -959,13 +980,13 @@ class AsyncOmniEngine:
|
||||
def _assemble_stage_pools(
|
||||
self,
|
||||
stage_plans: Sequence[LogicalStageInitPlan],
|
||||
initialized_clients_by_stage: Mapping[int, Sequence[Any | None]],
|
||||
initialized_clients_by_stage: Mapping[int, Sequence[StagePoolClient | None]],
|
||||
) -> list[StagePool]:
|
||||
"""Assemble logical stage pools and update top-level stage metadata."""
|
||||
|
||||
stage_pools: list[StagePool] = []
|
||||
default_sampling_params_list: list[Any] = []
|
||||
stage_metadata_list: list[dict[str, Any]] = []
|
||||
default_sampling_params_list: list[OmniSamplingParams] = []
|
||||
stage_metadata_list: list[StageRuntimeInfo] = []
|
||||
|
||||
for plan in stage_plans:
|
||||
replica_clients = initialized_clients_by_stage[plan.stage_idx]
|
||||
@@ -973,7 +994,7 @@ class AsyncOmniEngine:
|
||||
if first_client is None:
|
||||
raise RuntimeError(f"Stage {plan.stage_idx} initialization completed with a missing client")
|
||||
|
||||
clients = [client for client in replica_clients if client is not None]
|
||||
clients: list[StagePoolClient] = [client for client in replica_clients if client is not None]
|
||||
stage_vllm_config = None
|
||||
output_processor = None
|
||||
if plan.replicas[0].metadata.stage_type != "diffusion":
|
||||
@@ -991,11 +1012,11 @@ class AsyncOmniEngine:
|
||||
)
|
||||
default_sampling_params_list.append(first_client.default_sampling_params)
|
||||
stage_metadata_list.append(
|
||||
{
|
||||
"final_output": first_client.final_output,
|
||||
"final_output_type": first_client.final_output_type,
|
||||
"stage_type": first_client.stage_type,
|
||||
}
|
||||
StageRuntimeInfo(
|
||||
final_output=first_client.final_output,
|
||||
final_output_type=first_client.final_output_type,
|
||||
stage_type=first_client.stage_type,
|
||||
)
|
||||
)
|
||||
|
||||
self.default_sampling_params_list = list(default_sampling_params_list)
|
||||
@@ -1033,7 +1054,7 @@ class AsyncOmniEngine:
|
||||
|
||||
stage_pools: list[StagePool] = []
|
||||
input_processor: InputProcessor | None = None
|
||||
initialized_clients_by_stage: dict[int, list[Any | None]] = {
|
||||
initialized_clients_by_stage: dict[int, list[StagePoolClient | None]] = {
|
||||
plan.stage_idx: [None] * len(plan.replicas) for plan in stage_plans
|
||||
}
|
||||
|
||||
@@ -1071,7 +1092,7 @@ class AsyncOmniEngine:
|
||||
self.prompt_expand_func = prompt_expand_func
|
||||
|
||||
# Derive logical-stage views for external readers (entrypoints/async_omni.py).
|
||||
self.stage_clients = [pool.stage_client for pool in self.stage_pools]
|
||||
self.stage_clients = [cast(StageClient, pool.stage_client) for pool in self.stage_pools]
|
||||
self.stage_vllm_configs = [pool.stage_vllm_config for pool in self.stage_pools]
|
||||
self.output_processors = [pool.output_processor for pool in self.stage_pools]
|
||||
|
||||
@@ -1079,7 +1100,7 @@ class AsyncOmniEngine:
|
||||
supported_tasks: set[str] = set()
|
||||
if any(getattr(pool.stage_client, "is_comprehension", False) for pool in self.stage_pools):
|
||||
supported_tasks.add("generate")
|
||||
if any(m.get("final_output_type") == "audio" for m in self.stage_metadata):
|
||||
if any(m.final_output_type == "audio" for m in self.stage_metadata):
|
||||
supported_tasks.add("speech")
|
||||
self.supported_tasks = tuple(supported_tasks) if supported_tasks else ("generate",)
|
||||
|
||||
@@ -1127,7 +1148,7 @@ class AsyncOmniEngine:
|
||||
logger.exception("[AsyncOmniEngine] Orchestrator thread crashed")
|
||||
error_text = str(e) or "Orchestrator thread crashed"
|
||||
try:
|
||||
error_msg = {"type": "error", "error": error_text, "fatal": True}
|
||||
error_msg = ErrorMessage(error=error_text, fatal=True)
|
||||
if self.output_queue is not None:
|
||||
self.output_queue.sync_q.put_nowait(error_msg)
|
||||
if self.rpc_output_queue is not None:
|
||||
@@ -1194,11 +1215,13 @@ class AsyncOmniEngine:
|
||||
reasoning_ended: bool | None = None,
|
||||
*,
|
||||
resumable: bool = False,
|
||||
message_type: str = "add_request",
|
||||
) -> dict[str, Any]:
|
||||
message_type: Literal["add_request", "streaming_update"] = "add_request",
|
||||
) -> StageSubmissionMessage:
|
||||
"""Build an add_request message after stage-0 preprocessing."""
|
||||
effective_sampling_params_list = (
|
||||
list(sampling_params_list) if sampling_params_list is not None else list(self.default_sampling_params_list)
|
||||
effective_sampling_params_list: list[OmniSamplingParams] = (
|
||||
list(cast(Sequence[OmniSamplingParams], sampling_params_list))
|
||||
if sampling_params_list is not None
|
||||
else list(self.default_sampling_params_list)
|
||||
)
|
||||
if not effective_sampling_params_list:
|
||||
raise ValueError(
|
||||
@@ -1210,7 +1233,7 @@ class AsyncOmniEngine:
|
||||
# dict, e.g. for multi_modal_data).
|
||||
original_prompt = prompt
|
||||
|
||||
stage_type = self.stage_metadata[0].get("stage_type")
|
||||
stage_type = self.stage_metadata[0].stage_type
|
||||
output_prompt_text: Any = None
|
||||
_preprocess_ms = 0.0
|
||||
if stage_type != "diffusion" and not isinstance(prompt, EngineCoreRequest):
|
||||
@@ -1261,17 +1284,17 @@ class AsyncOmniEngine:
|
||||
output_prompt_text = original_prompt.get("prompt")
|
||||
prompt = request
|
||||
|
||||
return {
|
||||
"type": message_type,
|
||||
"request_id": request_id,
|
||||
"prompt": prompt,
|
||||
"original_prompt": original_prompt,
|
||||
"output_prompt_text": output_prompt_text,
|
||||
"sampling_params_list": effective_sampling_params_list,
|
||||
"final_stage_id": final_stage_id,
|
||||
"preprocess_ms": _preprocess_ms,
|
||||
"enqueue_ts": time.perf_counter(),
|
||||
}
|
||||
return StageSubmissionMessage(
|
||||
type=message_type,
|
||||
request_id=request_id,
|
||||
prompt=prompt,
|
||||
original_prompt=original_prompt,
|
||||
output_prompt_text=output_prompt_text,
|
||||
sampling_params_list=effective_sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
preprocess_ms=_preprocess_ms,
|
||||
enqueue_ts=time.perf_counter(),
|
||||
)
|
||||
|
||||
def _enqueue_cfg_companions(
|
||||
self,
|
||||
@@ -1311,15 +1334,14 @@ class AsyncOmniEngine:
|
||||
# deferred to Orchestrator._handle_add_companion, which routes
|
||||
# admission through StagePool.submit_initial(..., affinity_request_id=...).
|
||||
self.request_queue.sync_q.put_nowait(
|
||||
{
|
||||
"type": "add_companion_request",
|
||||
"companion_id": cid,
|
||||
"parent_id": parent_id,
|
||||
"role": ep.role,
|
||||
"prompt": request,
|
||||
"companion_prompt_text": companion_prompt,
|
||||
"sampling_params_list": companion_spl,
|
||||
}
|
||||
AddCompanionRequestMessage(
|
||||
companion_id=cid,
|
||||
parent_id=parent_id,
|
||||
role=ep.role,
|
||||
prompt=request,
|
||||
companion_prompt_text=companion_prompt,
|
||||
sampling_params_list=companion_spl,
|
||||
)
|
||||
)
|
||||
|
||||
logger.info(
|
||||
@@ -1766,8 +1788,8 @@ class AsyncOmniEngine:
|
||||
# CFG companion expansion: create and enqueue companion requests
|
||||
# so the AR stage also generates their KV caches.
|
||||
if self.prompt_expand_func is not None and final_stage_id > 0:
|
||||
original_prompt = msg.get("original_prompt", prompt)
|
||||
effective_spl = msg.get("sampling_params_list", [])
|
||||
original_prompt = msg.original_prompt
|
||||
effective_spl = msg.sampling_params_list
|
||||
stage0_params = effective_spl[0] if effective_spl else None
|
||||
if stage0_params is not None:
|
||||
self._enqueue_cfg_companions(request_id, original_prompt, stage0_params, effective_spl)
|
||||
@@ -1854,7 +1876,7 @@ class AsyncOmniEngine:
|
||||
resumable=resumable,
|
||||
)
|
||||
|
||||
def try_get_output(self, timeout: float = 0.001) -> dict[str, Any] | None:
|
||||
def try_get_output(self, timeout: float = 0.001) -> EngineQueueMessage | None:
|
||||
"""Read one output message from the Orchestrator output queue."""
|
||||
if self.output_queue is None:
|
||||
return None
|
||||
@@ -1865,7 +1887,7 @@ class AsyncOmniEngine:
|
||||
raise RuntimeError("Orchestrator died unexpectedly. See logs above.")
|
||||
return None
|
||||
|
||||
async def try_get_output_async(self) -> dict[str, Any] | None:
|
||||
async def try_get_output_async(self) -> EngineQueueMessage | None:
|
||||
"""Async read from the Orchestrator output queue."""
|
||||
if self.output_queue is None:
|
||||
return None
|
||||
@@ -1876,7 +1898,7 @@ class AsyncOmniEngine:
|
||||
raise RuntimeError("Orchestrator died unexpectedly. See logs above.")
|
||||
return None
|
||||
|
||||
def get_stage_metadata(self, stage_id: int) -> dict[str, Any]:
|
||||
def get_stage_metadata(self, stage_id: int) -> StageRuntimeInfo:
|
||||
"""Get cached metadata for a stage."""
|
||||
return self.stage_metadata[stage_id]
|
||||
|
||||
@@ -1884,12 +1906,7 @@ class AsyncOmniEngine:
|
||||
"""Send abort message to the Orchestrator."""
|
||||
if self.request_queue is None:
|
||||
raise RuntimeError("request_queue is not initialized")
|
||||
self.request_queue.sync_q.put_nowait(
|
||||
{
|
||||
"type": "abort",
|
||||
"request_ids": request_ids,
|
||||
}
|
||||
)
|
||||
self.request_queue.sync_q.put_nowait(AbortRequestMessage(request_ids=request_ids))
|
||||
|
||||
async def abort_async(self, request_ids: list[str]) -> None:
|
||||
"""Async abort API."""
|
||||
@@ -1914,14 +1931,14 @@ class AsyncOmniEngine:
|
||||
raise RuntimeError("rpc_output_queue is not initialized")
|
||||
|
||||
rpc_id = uuid.uuid4().hex
|
||||
msg = {
|
||||
"type": "collective_rpc",
|
||||
"rpc_id": rpc_id,
|
||||
"method": method,
|
||||
"args": tuple(args),
|
||||
"kwargs": kwargs or {},
|
||||
"stage_ids": stage_ids,
|
||||
}
|
||||
msg = CollectiveRPCRequestMessage(
|
||||
rpc_id=rpc_id,
|
||||
method=method,
|
||||
timeout=timeout,
|
||||
args=tuple(args),
|
||||
kwargs=kwargs or {},
|
||||
stage_ids=stage_ids,
|
||||
)
|
||||
|
||||
with self._rpc_lock:
|
||||
self.request_queue.sync_q.put_nowait(msg)
|
||||
@@ -1934,25 +1951,25 @@ class AsyncOmniEngine:
|
||||
except queue.Empty as exc:
|
||||
raise TimeoutError(f"collective_rpc timed out after {timeout} seconds") from exc
|
||||
|
||||
if result_msg.get("type") == "error":
|
||||
raise RuntimeError(result_msg.get("error", "Orchestrator returned an error message"))
|
||||
if isinstance(result_msg, ErrorMessage):
|
||||
raise RuntimeError(result_msg.error)
|
||||
|
||||
if result_msg.get("type") != "collective_rpc_result":
|
||||
if not isinstance(result_msg, CollectiveRPCResultMessage):
|
||||
logger.warning(
|
||||
"[AsyncOmniEngine] Dropping unexpected rpc queue message type=%s",
|
||||
result_msg.get("type"),
|
||||
getattr(result_msg, "type", type(result_msg).__name__),
|
||||
)
|
||||
continue
|
||||
|
||||
if result_msg.get("rpc_id") != rpc_id:
|
||||
if result_msg.rpc_id != rpc_id:
|
||||
logger.warning(
|
||||
"[AsyncOmniEngine] Dropping mismatched rpc result rpc_id=%s expected=%s",
|
||||
result_msg.get("rpc_id"),
|
||||
result_msg.rpc_id,
|
||||
rpc_id,
|
||||
)
|
||||
continue
|
||||
|
||||
return list(result_msg.get("results", []))
|
||||
return list(result_msg.results)
|
||||
|
||||
async def collective_rpc_async(
|
||||
self,
|
||||
@@ -1991,7 +2008,7 @@ class AsyncOmniEngine:
|
||||
logger.info("[AsyncOmniEngine] Shutting down Orchestrator")
|
||||
try:
|
||||
if self.request_queue is not None:
|
||||
self.request_queue.sync_q.put_nowait({"type": "shutdown"})
|
||||
self.request_queue.sync_q.put_nowait(ShutdownRequestMessage())
|
||||
except Exception:
|
||||
pass
|
||||
if self.is_alive():
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
import msgspec
|
||||
from vllm.inputs import PromptType
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
from vllm_omni.metrics.stats import StageRequestStats as StageRequestMetrics
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
|
||||
class EngineQueueMessage(msgspec.Struct, forbid_unknown_fields=True):
|
||||
pass
|
||||
|
||||
|
||||
class StageSubmissionMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["add_request", "streaming_update"]
|
||||
request_id: str
|
||||
prompt: EngineCoreRequest | PromptType
|
||||
original_prompt: EngineCoreRequest | PromptType
|
||||
output_prompt_text: object | None
|
||||
sampling_params_list: list[OmniSamplingParams]
|
||||
final_stage_id: int
|
||||
preprocess_ms: float
|
||||
enqueue_ts: float
|
||||
|
||||
|
||||
class AddCompanionRequestMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["add_companion_request"] = "add_companion_request"
|
||||
companion_id: str
|
||||
parent_id: str
|
||||
role: str
|
||||
prompt: EngineCoreRequest
|
||||
companion_prompt_text: object | None
|
||||
sampling_params_list: list[OmniSamplingParams]
|
||||
|
||||
|
||||
class AbortRequestMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["abort"] = "abort"
|
||||
request_ids: list[str]
|
||||
|
||||
|
||||
class CollectiveRPCRequestMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["collective_rpc"] = "collective_rpc"
|
||||
rpc_id: str
|
||||
method: str
|
||||
timeout: float | None = None
|
||||
args: tuple[object, ...]
|
||||
kwargs: dict[str, object]
|
||||
stage_ids: list[int] | None
|
||||
|
||||
|
||||
class ShutdownRequestMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["shutdown"] = "shutdown"
|
||||
|
||||
|
||||
class ErrorMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["error"] = "error"
|
||||
error: str
|
||||
fatal: bool = False
|
||||
request_id: str | None = None
|
||||
stage_id: int | None = None
|
||||
|
||||
|
||||
class OutputMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["output"] = "output"
|
||||
request_id: str
|
||||
stage_id: int
|
||||
engine_outputs: OmniRequestOutput
|
||||
metrics: StageRequestMetrics | None = None
|
||||
finished: bool
|
||||
stage_submit_ts: float | None = None
|
||||
|
||||
|
||||
class StageMetricsMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["stage_metrics"] = "stage_metrics"
|
||||
request_id: str
|
||||
stage_id: int
|
||||
metrics: StageRequestMetrics
|
||||
stage_submit_ts: float | None = None
|
||||
|
||||
|
||||
class CollectiveRPCResultMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["collective_rpc_result"] = "collective_rpc_result"
|
||||
rpc_id: str
|
||||
method: str
|
||||
stage_ids: list[int]
|
||||
results: list[object]
|
||||
+233
-175
@@ -24,6 +24,18 @@ from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.engine import OmniEngineCoreRequest
|
||||
from vllm_omni.engine.cfg_companion_tracker import CfgCompanionTracker
|
||||
from vllm_omni.engine.messages import (
|
||||
AbortRequestMessage,
|
||||
AddCompanionRequestMessage,
|
||||
CollectiveRPCRequestMessage,
|
||||
CollectiveRPCResultMessage,
|
||||
EngineQueueMessage,
|
||||
ErrorMessage,
|
||||
OutputMessage,
|
||||
ShutdownRequestMessage,
|
||||
StageMetricsMessage,
|
||||
StageSubmissionMessage,
|
||||
)
|
||||
from vllm_omni.engine.serialization import serialize_additional_information
|
||||
from vllm_omni.engine.stage_pool import StagePool
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
@@ -115,9 +127,9 @@ class Orchestrator:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
request_async_queue: janus.AsyncQueue[dict[str, Any]],
|
||||
output_async_queue: janus.AsyncQueue[dict[str, Any]],
|
||||
rpc_async_queue: janus.AsyncQueue[dict[str, Any]],
|
||||
request_async_queue: janus.AsyncQueue[EngineQueueMessage],
|
||||
output_async_queue: janus.AsyncQueue[EngineQueueMessage],
|
||||
rpc_async_queue: janus.AsyncQueue[EngineQueueMessage],
|
||||
stage_pools: list[StagePool],
|
||||
*,
|
||||
async_chunk: bool = False,
|
||||
@@ -196,36 +208,38 @@ class Orchestrator:
|
||||
"""Read messages from the main thread via request_async_queue."""
|
||||
while True:
|
||||
msg = await self.request_async_queue.get()
|
||||
msg_type = msg.get("type")
|
||||
|
||||
if msg_type == "add_request":
|
||||
await self._handle_add_request(msg)
|
||||
elif msg_type == "streaming_update":
|
||||
await self._handle_streaming_update(msg)
|
||||
elif msg_type == "add_companion_request":
|
||||
if isinstance(msg, StageSubmissionMessage):
|
||||
if msg.type == "add_request":
|
||||
await self._handle_add_request(msg)
|
||||
elif msg.type == "streaming_update":
|
||||
await self._handle_streaming_update(msg)
|
||||
else:
|
||||
logger.warning("[Orchestrator] Unknown stage submission type: %s", msg.type)
|
||||
elif isinstance(msg, AddCompanionRequestMessage):
|
||||
await self._handle_add_companion(msg)
|
||||
elif msg_type == "abort":
|
||||
elif isinstance(msg, AbortRequestMessage):
|
||||
await self._handle_abort(msg)
|
||||
elif msg_type == "collective_rpc":
|
||||
elif isinstance(msg, CollectiveRPCRequestMessage):
|
||||
await self._handle_collective_rpc(msg)
|
||||
elif msg_type == "shutdown":
|
||||
elif isinstance(msg, ShutdownRequestMessage):
|
||||
logger.info("[Orchestrator] Received shutdown signal")
|
||||
self._shutdown_event.set()
|
||||
self._shutdown_stages()
|
||||
break
|
||||
else:
|
||||
logger.warning("[Orchestrator] Unknown message type: %s", msg_type)
|
||||
logger.warning("[Orchestrator] Unknown message type: %s", type(msg).__name__)
|
||||
|
||||
async def _handle_add_request(self, msg: dict[str, Any]) -> None:
|
||||
async def _handle_add_request(self, msg: StageSubmissionMessage) -> None:
|
||||
"""Handle an add_request message from the main thread."""
|
||||
stage_id = 0
|
||||
request_id = msg["request_id"]
|
||||
prompt = msg["prompt"]
|
||||
original_prompt = msg.get("original_prompt", prompt)
|
||||
sampling_params_list = msg["sampling_params_list"]
|
||||
request_id = msg.request_id
|
||||
prompt = msg.prompt
|
||||
original_prompt = msg.original_prompt
|
||||
sampling_params_list = msg.sampling_params_list
|
||||
if not sampling_params_list:
|
||||
raise ValueError(f"Missing sampling params for stage 0. Got {len(sampling_params_list)} stage params.")
|
||||
final_stage_id = msg["final_stage_id"]
|
||||
final_stage_id = msg.final_stage_id
|
||||
|
||||
logger.debug(
|
||||
"[Orchestrator] _handle_add_request: stage=%s req=%s "
|
||||
@@ -249,27 +263,27 @@ class Orchestrator:
|
||||
self.request_states[request_id] = req_state
|
||||
req_state.streaming.enabled = bool(getattr(prompt, "resumable", False))
|
||||
req_state.stage_submit_ts[stage_id] = _time.time()
|
||||
enqueue_ts = msg.get("enqueue_ts", 0.0)
|
||||
enqueue_ts = msg.enqueue_ts
|
||||
if enqueue_ts > 0:
|
||||
req_state.pipeline_timings["queue_wait_ms"] = (_time.perf_counter() - enqueue_ts) * 1000.0
|
||||
preprocess_ms = msg.get("preprocess_ms", 0.0)
|
||||
preprocess_ms = msg.preprocess_ms
|
||||
if preprocess_ms > 0:
|
||||
req_state.pipeline_timings["preprocess_ms"] = preprocess_ms
|
||||
await self.stage_pools[stage_id].submit_initial(
|
||||
request_id,
|
||||
req_state,
|
||||
prompt,
|
||||
prompt_text=msg.get("output_prompt_text"),
|
||||
prompt_text=msg.output_prompt_text,
|
||||
)
|
||||
|
||||
if self.async_chunk and stage_id == 0 and final_stage_id > 0:
|
||||
await self._prewarm_async_chunk_stages(request_id, prompt, req_state)
|
||||
|
||||
async def _handle_streaming_update(self, msg: dict[str, Any]) -> None:
|
||||
async def _handle_streaming_update(self, msg: StageSubmissionMessage) -> None:
|
||||
"""Handle a streaming_update message for an existing request."""
|
||||
stage_id = 0
|
||||
request_id = msg["request_id"]
|
||||
request = msg["prompt"]
|
||||
request_id = msg.request_id
|
||||
request = msg.prompt
|
||||
|
||||
req_state = self.request_states.get(request_id)
|
||||
if req_state is None:
|
||||
@@ -277,13 +291,22 @@ class Orchestrator:
|
||||
"[Orchestrator] streaming_update for unknown req=%s, falling back to add_request",
|
||||
request_id,
|
||||
)
|
||||
fallback_msg = dict(msg)
|
||||
fallback_msg["type"] = "add_request"
|
||||
fallback_msg = StageSubmissionMessage(
|
||||
type="add_request",
|
||||
request_id=msg.request_id,
|
||||
prompt=msg.prompt,
|
||||
original_prompt=msg.original_prompt,
|
||||
output_prompt_text=msg.output_prompt_text,
|
||||
sampling_params_list=msg.sampling_params_list,
|
||||
final_stage_id=msg.final_stage_id,
|
||||
preprocess_ms=msg.preprocess_ms,
|
||||
enqueue_ts=msg.enqueue_ts,
|
||||
)
|
||||
await self._handle_add_request(fallback_msg)
|
||||
return
|
||||
|
||||
if "sampling_params_list" in msg and msg["sampling_params_list"]:
|
||||
req_state.sampling_params_list = msg["sampling_params_list"]
|
||||
if msg.sampling_params_list:
|
||||
req_state.sampling_params_list = msg.sampling_params_list
|
||||
|
||||
req_state.streaming.enabled = True
|
||||
req_state.stage_submit_ts[stage_id] = _time.time()
|
||||
@@ -291,16 +314,16 @@ class Orchestrator:
|
||||
request_id,
|
||||
req_state,
|
||||
request,
|
||||
prompt_text=msg.get("output_prompt_text"),
|
||||
prompt_text=msg.output_prompt_text,
|
||||
)
|
||||
|
||||
async def _handle_add_companion(self, msg: dict[str, Any]) -> None:
|
||||
async def _handle_add_companion(self, msg: AddCompanionRequestMessage) -> None:
|
||||
"""Handle an add_companion_request message: submit companion to stage 0."""
|
||||
companion_id = msg["companion_id"]
|
||||
parent_id = msg["parent_id"]
|
||||
role = msg["role"]
|
||||
companion_prompt = msg["prompt"]
|
||||
sampling_params_list = msg["sampling_params_list"]
|
||||
companion_id = msg.companion_id
|
||||
parent_id = msg.parent_id
|
||||
role = msg.role
|
||||
companion_prompt = msg.prompt
|
||||
sampling_params_list = msg.sampling_params_list
|
||||
|
||||
parent_state = self.request_states.get(parent_id)
|
||||
if parent_state is None:
|
||||
@@ -326,7 +349,7 @@ class Orchestrator:
|
||||
companion_id,
|
||||
companion_state,
|
||||
companion_prompt,
|
||||
prompt_text=msg.get("companion_prompt_text"),
|
||||
prompt_text=msg.companion_prompt_text,
|
||||
affinity_request_id=parent_id,
|
||||
)
|
||||
|
||||
@@ -338,9 +361,9 @@ class Orchestrator:
|
||||
companion_replica_id,
|
||||
)
|
||||
|
||||
async def _handle_abort(self, msg: dict[str, Any]) -> None:
|
||||
async def _handle_abort(self, msg: AbortRequestMessage) -> None:
|
||||
"""Handle an abort message from the main thread."""
|
||||
request_ids = msg["request_ids"]
|
||||
request_ids = msg.request_ids
|
||||
await self._cleanup_request_ids(
|
||||
self._cfg_tracker.abort_parents(request_ids),
|
||||
abort=True,
|
||||
@@ -359,14 +382,14 @@ class Orchestrator:
|
||||
for pool in self.stage_pools:
|
||||
pool.release_bindings(request_ids)
|
||||
|
||||
async def _handle_collective_rpc(self, msg: dict[str, Any]) -> None:
|
||||
async def _handle_collective_rpc(self, msg: CollectiveRPCRequestMessage) -> None:
|
||||
"""Handle a control-plane RPC request from the main thread."""
|
||||
rpc_id = msg["rpc_id"]
|
||||
method = msg["method"]
|
||||
timeout = msg.get("timeout")
|
||||
args = tuple(msg.get("args", ()))
|
||||
kwargs = dict(msg.get("kwargs") or {})
|
||||
requested_stage_ids = msg.get("stage_ids")
|
||||
rpc_id = msg.rpc_id
|
||||
method = msg.method
|
||||
timeout = msg.timeout
|
||||
args = msg.args
|
||||
kwargs = dict(msg.kwargs)
|
||||
requested_stage_ids = msg.stage_ids
|
||||
|
||||
target_pools: list[StagePool] = []
|
||||
if requested_stage_ids is None:
|
||||
@@ -393,13 +416,12 @@ class Orchestrator:
|
||||
results.append(stage_result)
|
||||
|
||||
await self.rpc_async_queue.put(
|
||||
{
|
||||
"type": "collective_rpc_result",
|
||||
"rpc_id": rpc_id,
|
||||
"method": method,
|
||||
"stage_ids": stage_ids,
|
||||
"results": results,
|
||||
}
|
||||
CollectiveRPCResultMessage(
|
||||
rpc_id=rpc_id,
|
||||
method=method,
|
||||
stage_ids=stage_ids,
|
||||
results=results,
|
||||
)
|
||||
)
|
||||
|
||||
# ---- Orchestration loop ----
|
||||
@@ -469,13 +491,12 @@ class Orchestrator:
|
||||
for req_id, req_state in list(self.request_states.items()):
|
||||
if stage_id in req_state.stage_submit_ts:
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"error": str(e),
|
||||
"fatal": True,
|
||||
"request_id": req_id,
|
||||
"stage_id": stage_id,
|
||||
}
|
||||
ErrorMessage(
|
||||
error=str(e),
|
||||
fatal=True,
|
||||
request_id=req_id,
|
||||
stage_id=stage_id,
|
||||
)
|
||||
)
|
||||
self.request_states.pop(req_id, None)
|
||||
self._shutdown_event.set()
|
||||
@@ -534,12 +555,11 @@ class Orchestrator:
|
||||
else:
|
||||
parent_id = output.request_id
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"request_id": parent_id,
|
||||
"stage_id": stage_id,
|
||||
"error": output.error,
|
||||
}
|
||||
ErrorMessage(
|
||||
request_id=parent_id,
|
||||
stage_id=stage_id,
|
||||
error=output.error,
|
||||
)
|
||||
)
|
||||
await self._cleanup_request_ids(
|
||||
[parent_id, *self._cfg_tracker.cleanup_parent(parent_id)],
|
||||
@@ -596,25 +616,23 @@ class Orchestrator:
|
||||
|
||||
if self.stage_pools[stage_id].final_output:
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "output",
|
||||
"request_id": req_id,
|
||||
"stage_id": stage_id,
|
||||
"engine_outputs": output,
|
||||
"metrics": stage_metrics,
|
||||
"finished": finished and stage_id == req_state.final_stage_id,
|
||||
"stage_submit_ts": submit_ts,
|
||||
}
|
||||
OutputMessage(
|
||||
request_id=req_id,
|
||||
stage_id=stage_id,
|
||||
engine_outputs=output,
|
||||
metrics=stage_metrics,
|
||||
finished=finished and stage_id == req_state.final_stage_id,
|
||||
stage_submit_ts=submit_ts,
|
||||
)
|
||||
)
|
||||
elif stage_metrics is not None:
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "stage_metrics",
|
||||
"request_id": req_id,
|
||||
"stage_id": stage_id,
|
||||
"metrics": stage_metrics,
|
||||
"stage_submit_ts": submit_ts,
|
||||
}
|
||||
StageMetricsMessage(
|
||||
request_id=req_id,
|
||||
stage_id=stage_id,
|
||||
metrics=stage_metrics,
|
||||
stage_submit_ts=submit_ts,
|
||||
)
|
||||
)
|
||||
|
||||
if self._pd_pair is not None and finished and stage_id == self._pd_pair[0]:
|
||||
@@ -775,79 +793,120 @@ class Orchestrator:
|
||||
"""Forward output from the current logical stage to the next one."""
|
||||
next_logical = src_stage_id + 1
|
||||
next_pool = self.stage_pools[next_logical]
|
||||
next_client = next_pool.stage_client
|
||||
|
||||
if next_pool.stage_type == "diffusion":
|
||||
await self._forward_to_diffusion_stage(
|
||||
req_id,
|
||||
src_stage_id,
|
||||
output,
|
||||
req_state,
|
||||
)
|
||||
else:
|
||||
await self._forward_to_llm_stage(
|
||||
req_id,
|
||||
src_stage_id,
|
||||
output,
|
||||
req_state,
|
||||
is_streaming_session=is_streaming_session,
|
||||
is_final_update=is_final_update,
|
||||
)
|
||||
|
||||
async def _forward_to_diffusion_stage(
|
||||
self,
|
||||
req_id: str,
|
||||
src_stage_id: int,
|
||||
output: Any,
|
||||
req_state: OrchestratorRequestState,
|
||||
) -> None:
|
||||
"""Forward output from an LLM stage to the next diffusion stage."""
|
||||
next_logical = src_stage_id + 1
|
||||
next_pool = self.stage_pools[next_logical]
|
||||
params = req_state.sampling_params_list[next_logical]
|
||||
source_outputs = [output]
|
||||
already_submitted = self._next_stage_already_submitted(src_stage_id, req_state)
|
||||
|
||||
diffusion_client = next_pool.stage_client
|
||||
if diffusion_client.custom_process_input_func is not None:
|
||||
_t_ar2d = _time.perf_counter()
|
||||
diffusion_prompt = diffusion_client.custom_process_input_func(
|
||||
source_outputs,
|
||||
req_state.prompt,
|
||||
getattr(diffusion_client, "requires_multimodal_data", False),
|
||||
)
|
||||
_dt_ar2d = (_time.perf_counter() - _t_ar2d) * 1000
|
||||
req_state.pipeline_timings["ar2diffusion_ms"] = _dt_ar2d
|
||||
logger.info(
|
||||
"[Orchestrator] ar2diffusion req=%s wall_time=%.3fms stage=%d->%d",
|
||||
req_id,
|
||||
_dt_ar2d,
|
||||
src_stage_id,
|
||||
next_logical,
|
||||
)
|
||||
if isinstance(diffusion_prompt, list):
|
||||
if not diffusion_prompt:
|
||||
error_output = OmniRequestOutput.from_error(
|
||||
req_id,
|
||||
f"Stage-{src_stage_id} produced no valid inputs for diffusion stage-{next_logical}",
|
||||
)
|
||||
logger.warning(
|
||||
"[Orchestrator] req=%s stage=%d produced empty diffusion inputs for stage=%d; "
|
||||
"routing terminal error output",
|
||||
req_id,
|
||||
src_stage_id,
|
||||
next_logical,
|
||||
)
|
||||
await self.output_async_queue.put(
|
||||
OutputMessage(
|
||||
request_id=req_id,
|
||||
stage_id=next_logical,
|
||||
engine_outputs=error_output,
|
||||
metrics=None,
|
||||
finished=True,
|
||||
)
|
||||
)
|
||||
await self._cleanup_request_ids(
|
||||
[req_id, *self._cfg_tracker.cleanup_parent(req_id)],
|
||||
)
|
||||
return
|
||||
if already_submitted and len(diffusion_prompt) == 1:
|
||||
diffusion_prompt = diffusion_prompt[0]
|
||||
else:
|
||||
diffusion_prompt = req_state.prompt
|
||||
|
||||
if already_submitted:
|
||||
await next_pool.submit_update(req_id, req_state, diffusion_prompt)
|
||||
else:
|
||||
await next_pool.submit_initial(
|
||||
req_id,
|
||||
req_state,
|
||||
diffusion_prompt,
|
||||
submit_kwargs={
|
||||
"kv_sender_info": self._build_kv_sender_info(
|
||||
list(getattr(diffusion_client, "engine_input_source", None) or [src_stage_id]),
|
||||
request_id=req_id,
|
||||
)
|
||||
},
|
||||
params_override=self._maybe_clone_diffusion_params_for_cfg(req_id, params),
|
||||
)
|
||||
req_state.stage_submit_ts[next_logical] = _time.time()
|
||||
|
||||
async def _forward_to_llm_stage(
|
||||
self,
|
||||
req_id: str,
|
||||
src_stage_id: int,
|
||||
output: Any,
|
||||
req_state: OrchestratorRequestState,
|
||||
*,
|
||||
is_streaming_session: bool = False,
|
||||
is_final_update: bool = False,
|
||||
) -> None:
|
||||
"""Forward output from the current stage to the next LLM stage."""
|
||||
next_logical = src_stage_id + 1
|
||||
next_pool = self.stage_pools[next_logical]
|
||||
params = req_state.sampling_params_list[next_logical]
|
||||
source_outputs = [output]
|
||||
next_stage_resumable = is_streaming_session and not is_final_update
|
||||
already_submitted = self._next_stage_already_submitted(src_stage_id, req_state)
|
||||
requires_multimodal_data = getattr(next_client, "requires_multimodal_data", False)
|
||||
|
||||
if next_pool.stage_type == "diffusion":
|
||||
if next_client.custom_process_input_func is not None:
|
||||
_t_ar2d = _time.perf_counter()
|
||||
diffusion_prompt = next_client.custom_process_input_func(
|
||||
source_outputs,
|
||||
req_state.prompt,
|
||||
requires_multimodal_data,
|
||||
)
|
||||
_dt_ar2d = (_time.perf_counter() - _t_ar2d) * 1000
|
||||
req_state.pipeline_timings["ar2diffusion_ms"] = _dt_ar2d
|
||||
logger.info(
|
||||
"[Orchestrator] ar2diffusion req=%s wall_time=%.3fms stage=%d->%d",
|
||||
req_id,
|
||||
_dt_ar2d,
|
||||
src_stage_id,
|
||||
next_logical,
|
||||
)
|
||||
if isinstance(diffusion_prompt, list):
|
||||
if not diffusion_prompt:
|
||||
error_output = OmniRequestOutput.from_error(
|
||||
req_id,
|
||||
f"Stage-{src_stage_id} produced no valid inputs for diffusion stage-{next_logical}",
|
||||
)
|
||||
logger.warning(
|
||||
"[Orchestrator] req=%s stage=%d produced empty diffusion inputs for stage=%d; "
|
||||
"routing terminal error output",
|
||||
req_id,
|
||||
src_stage_id,
|
||||
next_logical,
|
||||
)
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "output",
|
||||
"request_id": req_id,
|
||||
"stage_id": next_logical,
|
||||
"engine_outputs": error_output,
|
||||
"metrics": None,
|
||||
"finished": True,
|
||||
}
|
||||
)
|
||||
await self._cleanup_request_ids(
|
||||
[req_id, *self._cfg_tracker.cleanup_parent(req_id)],
|
||||
)
|
||||
return
|
||||
if already_submitted and len(diffusion_prompt) == 1:
|
||||
diffusion_prompt = diffusion_prompt[0]
|
||||
else:
|
||||
diffusion_prompt = req_state.prompt
|
||||
|
||||
if already_submitted:
|
||||
await next_pool.submit_update(req_id, req_state, diffusion_prompt)
|
||||
else:
|
||||
await next_pool.submit_initial(
|
||||
req_id,
|
||||
req_state,
|
||||
diffusion_prompt,
|
||||
submit_kwargs={
|
||||
"kv_sender_info": self._build_kv_sender_info(
|
||||
list(getattr(next_client, "engine_input_source", None) or [src_stage_id]),
|
||||
request_id=req_id,
|
||||
)
|
||||
},
|
||||
params_override=self._maybe_clone_diffusion_params_for_cfg(req_id, params),
|
||||
)
|
||||
req_state.stage_submit_ts[next_logical] = _time.time()
|
||||
return
|
||||
|
||||
# PD disaggregation: prefill → decode routing uses original prompt + KV transfer params
|
||||
if self._pd_pair is not None and (src_stage_id, next_logical) == self._pd_pair:
|
||||
@@ -894,6 +953,7 @@ class Orchestrator:
|
||||
{},
|
||||
)[req_id] = req_state.pd_prefill_multimodal_output
|
||||
|
||||
next_client = next_pool.llm_stage_client
|
||||
try:
|
||||
next_inputs = next_client.process_engine_inputs(
|
||||
source_outputs,
|
||||
@@ -912,7 +972,7 @@ class Orchestrator:
|
||||
for next_input in next_inputs:
|
||||
# Only AR thinker stages consume encoder mm_features; downstream
|
||||
# (talker/code2wav/…) must not see them (avoids encoder-cache misses).
|
||||
model_stage = getattr(next_client, "model_stage", None)
|
||||
model_stage = next_client.model_stage
|
||||
mm_features = req_state.mm_features if model_stage == "thinker" else None
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=req_id,
|
||||
@@ -962,7 +1022,7 @@ class Orchestrator:
|
||||
req_state.prompt,
|
||||
submit_kwargs={
|
||||
"kv_sender_info": self._build_kv_sender_info(
|
||||
list(getattr(next_pool.stage_client, "engine_input_source", None) or [next_stage_id - 1]),
|
||||
list(next_pool.stage_client.engine_input_source or [next_stage_id - 1]),
|
||||
request_id=request_id,
|
||||
)
|
||||
},
|
||||
@@ -1009,14 +1069,14 @@ class Orchestrator:
|
||||
continue
|
||||
|
||||
sender_pool = self.stage_pools[sender_stage_id]
|
||||
sender_stage = sender_pool.get_bound_client(request_id) if request_id is not None else None
|
||||
if sender_stage is None:
|
||||
sender_stage = sender_pool.stage_client
|
||||
get_sender_info = getattr(sender_stage, "get_kv_sender_info", None)
|
||||
if not callable(get_sender_info):
|
||||
if sender_pool.stage_type == "diffusion":
|
||||
continue
|
||||
|
||||
sender_info = get_sender_info()
|
||||
sender_stage = sender_pool.get_bound_llm_client(request_id) if request_id is not None else None
|
||||
if sender_stage is None:
|
||||
sender_stage = sender_pool.llm_stage_client
|
||||
|
||||
sender_info = sender_stage.get_kv_sender_info()
|
||||
if not sender_info:
|
||||
logger.warning(
|
||||
"[Orchestrator] Stage-%s has no KV sender info available",
|
||||
@@ -1050,16 +1110,15 @@ class Orchestrator:
|
||||
msg = self.request_async_queue.get_nowait()
|
||||
except Exception:
|
||||
break
|
||||
if msg.get("type") == "add_request":
|
||||
req_id = msg["request_id"]
|
||||
if isinstance(msg, StageSubmissionMessage) and msg.type == "add_request":
|
||||
req_id = msg.request_id
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"error": self._fatal_error,
|
||||
"fatal": True,
|
||||
"request_id": req_id,
|
||||
"stage_id": self._fatal_error_stage_id,
|
||||
}
|
||||
ErrorMessage(
|
||||
error=self._fatal_error,
|
||||
fatal=True,
|
||||
request_id=req_id,
|
||||
stage_id=self._fatal_error_stage_id,
|
||||
)
|
||||
)
|
||||
notified.add(req_id)
|
||||
|
||||
@@ -1069,13 +1128,12 @@ class Orchestrator:
|
||||
for req_id in list(self.request_states):
|
||||
if req_id not in notified:
|
||||
await self.output_async_queue.put(
|
||||
{
|
||||
"type": "error",
|
||||
"error": self._fatal_error,
|
||||
"fatal": True,
|
||||
"request_id": req_id,
|
||||
"stage_id": self._fatal_error_stage_id,
|
||||
}
|
||||
ErrorMessage(
|
||||
error=self._fatal_error,
|
||||
fatal=True,
|
||||
request_id=req_id,
|
||||
stage_id=self._fatal_error_stage_id,
|
||||
)
|
||||
)
|
||||
self.request_states.pop(req_id, None)
|
||||
|
||||
|
||||
@@ -9,6 +9,9 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
from enum import Enum, Flag, StrEnum, auto
|
||||
from typing import Literal, TypeAlias
|
||||
|
||||
FinalOutputModalityType: TypeAlias = Literal["text", "image", "audio", "video"]
|
||||
|
||||
_MODALITY_ALIASES: dict[str, str] = {
|
||||
"speech": "audio",
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Shared stage-client typing for vLLM-Omni runtime surfaces."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, Any, Protocol
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.engine import EngineCoreOutput, EngineCoreOutputs, EngineCoreRequest
|
||||
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType, OmniTokensPrompt
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
from vllm_omni.engine.output_modality import FinalOutputModalityType
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
|
||||
|
||||
class StageClient(Protocol):
|
||||
"""Shared metadata and lifecycle surface for all stage clients.
|
||||
|
||||
This protocol intentionally covers the common attributes consumed by
|
||||
orchestration and entrypoint code. Backend-specific request APIs stay
|
||||
typed with the concrete client union.
|
||||
"""
|
||||
|
||||
stage_id: int
|
||||
replica_id: int
|
||||
stage_type: str
|
||||
final_output: bool
|
||||
final_output_type: FinalOutputModalityType | None
|
||||
default_sampling_params: OmniSamplingParams
|
||||
requires_multimodal_data: bool
|
||||
custom_process_input_func: Any | None
|
||||
engine_input_source: Sequence[int]
|
||||
is_comprehension: bool
|
||||
|
||||
def check_health(self) -> None: ...
|
||||
|
||||
def shutdown(self) -> None: ...
|
||||
|
||||
|
||||
class StageClientBase:
|
||||
"""Runtime nominal base for stage clients.
|
||||
|
||||
Keeping the runtime base separate from the protocol avoids Protocol-related
|
||||
MRO interference with concrete client super() calls.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class StagePoolClient(StageClient, Protocol):
|
||||
"""Common pool-facing client surface shared by every stage backend."""
|
||||
|
||||
async def abort_requests_async(self, request_ids: list[str]) -> None: ...
|
||||
|
||||
async def collective_rpc_async(
|
||||
self,
|
||||
method: str,
|
||||
timeout: float | None = None,
|
||||
args: tuple[Any, ...] = (),
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
) -> Any: ...
|
||||
|
||||
|
||||
class StagePoolLLMClient(StagePoolClient, Protocol):
|
||||
"""Pool-facing API for LLM-style stages."""
|
||||
|
||||
model_stage: str | None
|
||||
|
||||
async def add_request_async(self, request: EngineCoreRequest) -> None: ...
|
||||
|
||||
async def get_output_async(self) -> EngineCoreOutputs: ...
|
||||
|
||||
def set_engine_outputs(self, engine_outputs: EngineCoreOutput) -> None: ...
|
||||
|
||||
def process_engine_inputs(
|
||||
self,
|
||||
source_outputs: list[Any],
|
||||
prompt: Any = None,
|
||||
streaming_context: Any | None = None,
|
||||
) -> list[OmniTokensPrompt]: ...
|
||||
|
||||
def get_kv_sender_info(
|
||||
self,
|
||||
*,
|
||||
base_port: int = ...,
|
||||
kv_transfer_port_offset: int = ...,
|
||||
) -> dict[str, Any] | None: ...
|
||||
|
||||
|
||||
class StagePoolDiffusionClient(StagePoolClient, Protocol):
|
||||
"""Pool-facing API for diffusion stages."""
|
||||
|
||||
async def add_request_async(
|
||||
self,
|
||||
request_id: str,
|
||||
prompt: OmniPromptType,
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
kv_sender_info: dict[int, dict[str, Any]] | None = None,
|
||||
) -> None: ...
|
||||
|
||||
async def add_batch_request_async(
|
||||
self,
|
||||
request_id: str,
|
||||
prompts: list[OmniPromptType],
|
||||
sampling_params: OmniDiffusionSamplingParams,
|
||||
kv_sender_info: dict[int, dict[str, Any]] | None = None,
|
||||
) -> None: ...
|
||||
|
||||
def get_diffusion_output_nowait(self) -> OmniRequestOutput | None: ...
|
||||
@@ -23,6 +23,7 @@ from vllm.v1.engine.exceptions import EngineDeadError
|
||||
from vllm_omni.distributed.omni_connectors.utils.initialization import (
|
||||
KV_TRANSFER_PORT_OFFSET,
|
||||
)
|
||||
from vllm_omni.engine.stage_client import StageClientBase
|
||||
from vllm_omni.engine.stage_init_utils import StageMetadata
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -56,7 +57,7 @@ def _default_process_engine_inputs(
|
||||
]
|
||||
|
||||
|
||||
class StageEngineCoreClientBase:
|
||||
class StageEngineCoreClientBase(StageClientBase):
|
||||
"""Shared stage-aware behavior for async EngineCore clients.
|
||||
|
||||
The concrete transport/load-balancing behavior is supplied by the
|
||||
|
||||
@@ -5,11 +5,16 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import time as _time
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine import EngineCoreOutputs
|
||||
|
||||
from vllm_omni.engine.stage_client import (
|
||||
StagePoolClient,
|
||||
StagePoolDiffusionClient,
|
||||
StagePoolLLMClient,
|
||||
)
|
||||
from vllm_omni.metrics.stats import StageRequestStats as StageRequestMetrics
|
||||
from vllm_omni.metrics.stats import StageStats
|
||||
from vllm_omni.metrics.utils import count_tokens_from_outputs
|
||||
@@ -35,20 +40,20 @@ class StagePool:
|
||||
def __init__(
|
||||
self,
|
||||
stage_id: int,
|
||||
clients: Any | list[Any],
|
||||
clients: StagePoolClient | list[StagePoolClient],
|
||||
*,
|
||||
output_processor: Any = None,
|
||||
stage_vllm_config: Any = None,
|
||||
) -> None:
|
||||
if isinstance(clients, list):
|
||||
normalized_clients = list(clients)
|
||||
normalized_clients: list[StagePoolClient] = list(clients)
|
||||
else:
|
||||
normalized_clients = [clients]
|
||||
|
||||
if not normalized_clients:
|
||||
raise ValueError(f"StagePool for stage {stage_id} has no replicas")
|
||||
self.stage_id = stage_id
|
||||
self.clients: list[Any] = normalized_clients
|
||||
self.clients: list[StagePoolClient] = normalized_clients
|
||||
self._output_processor = output_processor
|
||||
self._stage_vllm_config = stage_vllm_config
|
||||
self._next_replica_id = 0
|
||||
@@ -63,16 +68,20 @@ class StagePool:
|
||||
|
||||
@property
|
||||
def stage_type(self) -> str | None:
|
||||
return getattr(self.stage_client, "stage_type", None)
|
||||
return self.stage_client.stage_type
|
||||
|
||||
@property
|
||||
def final_output(self) -> bool:
|
||||
return bool(getattr(self.clients[0], "final_output", False))
|
||||
return self.clients[0].final_output
|
||||
|
||||
@property
|
||||
def stage_client(self) -> Any:
|
||||
def stage_client(self) -> StagePoolClient:
|
||||
return self.clients[0]
|
||||
|
||||
@property
|
||||
def llm_stage_client(self) -> StagePoolLLMClient:
|
||||
return cast(StagePoolLLMClient, self.stage_client)
|
||||
|
||||
@property
|
||||
def stage_vllm_config(self) -> Any:
|
||||
return self._stage_vllm_config
|
||||
@@ -87,13 +96,20 @@ class StagePool:
|
||||
"""Return the currently bound replica id for *request_id* if present."""
|
||||
return self._request_bindings.get(request_id)
|
||||
|
||||
def get_bound_client(self, request_id: str) -> Any | None:
|
||||
def get_bound_client(self, request_id: str) -> StagePoolClient | None:
|
||||
"""Return the currently bound client for *request_id* if present."""
|
||||
replica_id = self.get_bound_replica_id(request_id)
|
||||
if replica_id is None:
|
||||
return None
|
||||
return self.clients[replica_id]
|
||||
|
||||
def get_bound_llm_client(self, request_id: str) -> StagePoolLLMClient | None:
|
||||
"""Return the currently bound LLM client for *request_id* if present."""
|
||||
client = self.get_bound_client(request_id)
|
||||
if client is None:
|
||||
return None
|
||||
return cast(StagePoolLLMClient, client)
|
||||
|
||||
def release_binding(self, request_id: str) -> None:
|
||||
"""Drop the route binding for *request_id* in this stage."""
|
||||
self._request_bindings.pop(request_id, None)
|
||||
@@ -125,6 +141,12 @@ class StagePool:
|
||||
self._request_bindings[request_id] = chosen
|
||||
return chosen
|
||||
|
||||
def _llm_client(self, replica_id: int) -> StagePoolLLMClient:
|
||||
return cast(StagePoolLLMClient, self.clients[replica_id])
|
||||
|
||||
def _diffusion_client(self, replica_id: int) -> StagePoolDiffusionClient:
|
||||
return cast(StagePoolDiffusionClient, self.clients[replica_id])
|
||||
|
||||
# ---- Metrics ----
|
||||
|
||||
def build_stage_metrics(
|
||||
@@ -188,7 +210,7 @@ class StagePool:
|
||||
request_id,
|
||||
affinity_request_id=affinity_request_id,
|
||||
)
|
||||
client = self.clients[replica_id]
|
||||
client = self._diffusion_client(replica_id)
|
||||
if isinstance(request, list):
|
||||
await client.add_batch_request_async(request_id, request, params, **submit_kwargs)
|
||||
else:
|
||||
@@ -212,7 +234,7 @@ class StagePool:
|
||||
raise
|
||||
|
||||
try:
|
||||
await self.clients[replica_id].add_request_async(request, **submit_kwargs)
|
||||
await self._llm_client(replica_id).add_request_async(request, **submit_kwargs)
|
||||
except Exception:
|
||||
self.release_binding(request_id)
|
||||
rollback = getattr(self.output_processor, "remove_request", None)
|
||||
@@ -244,7 +266,7 @@ class StagePool:
|
||||
replica_id = self.select_replica_id(request_id)
|
||||
|
||||
if self.stage_type == "diffusion":
|
||||
await self.clients[replica_id].add_request_async(request_id, request, params)
|
||||
await self._diffusion_client(replica_id).add_request_async(request_id, request, params)
|
||||
else:
|
||||
# Refresh the shared output-processor state before yielding to the
|
||||
# stage client so streaming segments are merged against the latest
|
||||
@@ -256,12 +278,12 @@ class StagePool:
|
||||
request_index=0,
|
||||
queue=None,
|
||||
)
|
||||
await self.clients[replica_id].add_request_async(request)
|
||||
await self._llm_client(replica_id).add_request_async(request)
|
||||
return replica_id
|
||||
|
||||
# ---- Stage-local polling ----
|
||||
|
||||
async def _poll_stage_raw(self, client: Any) -> EngineCoreOutputs | None:
|
||||
async def _poll_stage_raw(self, client: StagePoolLLMClient) -> EngineCoreOutputs | None:
|
||||
"""Pull raw EngineCoreOutputs from a stage replica without processing."""
|
||||
outputs = await client.get_output_async()
|
||||
if not outputs.outputs:
|
||||
@@ -274,7 +296,7 @@ class StagePool:
|
||||
raw_outputs: EngineCoreOutputs,
|
||||
) -> list[Any]:
|
||||
"""Run the shared LLM output processor on one raw poll result."""
|
||||
client = self.clients[replica_id]
|
||||
client = self._llm_client(replica_id)
|
||||
processor = self.output_processor
|
||||
processed = processor.process_outputs(
|
||||
raw_outputs.outputs,
|
||||
@@ -297,7 +319,7 @@ class StagePool:
|
||||
timeout_s: float = 0.001,
|
||||
) -> EngineCoreOutputs | None:
|
||||
"""Poll raw EngineCore outputs from one LLM replica once."""
|
||||
client = self.clients[replica_id]
|
||||
client = self._llm_client(replica_id)
|
||||
try:
|
||||
return await asyncio.wait_for(
|
||||
self._poll_stage_raw(client),
|
||||
@@ -317,7 +339,7 @@ class StagePool:
|
||||
|
||||
def poll_diffusion_output(self, replica_id: int) -> Any | None:
|
||||
"""Drain one ready diffusion output from the given replica if present."""
|
||||
return self.clients[replica_id].get_diffusion_output_nowait()
|
||||
return self._diffusion_client(replica_id).get_diffusion_output_nowait()
|
||||
|
||||
# ---- Stage-local control plane ----
|
||||
|
||||
@@ -360,18 +382,12 @@ class StagePool:
|
||||
kwargs = dict(kwargs or {})
|
||||
client = self.clients[replica_id]
|
||||
try:
|
||||
if hasattr(client, "collective_rpc_async"):
|
||||
return await client.collective_rpc_async(
|
||||
method=method,
|
||||
timeout=timeout,
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
return {
|
||||
"supported": False,
|
||||
"todo": True,
|
||||
"reason": f"{client.__class__.__name__}.collective_rpc_async is not implemented yet",
|
||||
}
|
||||
return await client.collective_rpc_async(
|
||||
method=method,
|
||||
timeout=timeout,
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception(
|
||||
"[StagePool] collective_rpc failed: stage=%s replica=%s method=%s",
|
||||
|
||||
Reference in new issue
Block a user