[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
+10
-164
@@ -1,8 +1,10 @@
|
||||
import argparse
|
||||
import dataclasses
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs, EngineArgs
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.transformers_utils.gguf_utils import is_gguf
|
||||
|
||||
@@ -86,6 +88,12 @@ class OmniEngineArgs(EngineArgs):
|
||||
load_omni_general_plugins()
|
||||
super().__post_init__()
|
||||
|
||||
@classmethod
|
||||
def from_cli_args(cls, args: argparse.Namespace) -> "OmniEngineArgs":
|
||||
attrs = [attr.name for attr in dataclasses.fields(cls)]
|
||||
engine_args = cls(**{attr: getattr(args, attr) for attr in attrs if hasattr(args, attr)})
|
||||
return engine_args
|
||||
|
||||
def _ensure_omni_models_registered(self):
|
||||
if hasattr(self, "_omni_models_registered"):
|
||||
return True
|
||||
@@ -115,170 +123,8 @@ class OmniEngineArgs(EngineArgs):
|
||||
self._ensure_omni_models_registered()
|
||||
|
||||
# Keep compatibility when async args are constructed from partial payloads.
|
||||
limit_mm_per_prompt = getattr(self, "limit_mm_per_prompt", {})
|
||||
language_model_only = getattr(self, "language_model_only", False)
|
||||
enable_mm_embeds = getattr(self, "enable_mm_embeds", False)
|
||||
interleave_mm_strings = getattr(self, "interleave_mm_strings", False)
|
||||
media_io_kwargs = getattr(self, "media_io_kwargs", {})
|
||||
skip_mm_profiling = getattr(self, "skip_mm_profiling", False)
|
||||
mm_processor_kwargs = getattr(self, "mm_processor_kwargs", None)
|
||||
mm_processor_cache_gb = getattr(self, "mm_processor_cache_gb", 4)
|
||||
mm_processor_cache_type = getattr(self, "mm_processor_cache_type", None)
|
||||
mm_shm_cache_max_object_size_mb = getattr(self, "mm_shm_cache_max_object_size_mb", 128)
|
||||
mm_encoder_only = getattr(self, "mm_encoder_only", False)
|
||||
mm_encoder_tp_mode = getattr(self, "mm_encoder_tp_mode", "weights")
|
||||
mm_encoder_attn_backend = getattr(self, "mm_encoder_attn_backend", None)
|
||||
video_pruning_rate = getattr(self, "video_pruning_rate", 0.0)
|
||||
|
||||
# Build stage_connector_config from stage_connector_spec
|
||||
stage_connector_config = {
|
||||
"name": self.stage_connector_spec.get("name", "SharedMemoryConnector"),
|
||||
"extra": self.stage_connector_spec.get("extra", {}).copy(),
|
||||
}
|
||||
stage_connector_config["extra"]["stage_id"] = self.stage_id
|
||||
|
||||
# Create OmniModelConfig directly from engine args
|
||||
# Note: We pass the actual init parameters matching vLLM's EngineArgs.create_model_config()
|
||||
omni_config = OmniModelConfig(
|
||||
# Base ModelConfig fields (matching vLLM's EngineArgs.create_model_config)
|
||||
model=self.model,
|
||||
model_weights=self.model_weights,
|
||||
hf_config_path=self.hf_config_path,
|
||||
runner=self.runner,
|
||||
convert=self.convert,
|
||||
tokenizer=self.tokenizer,
|
||||
tokenizer_mode=self.tokenizer_mode,
|
||||
trust_remote_code=self.trust_remote_code,
|
||||
allowed_local_media_path=self.allowed_local_media_path,
|
||||
allowed_media_domains=self.allowed_media_domains,
|
||||
dtype=self.dtype,
|
||||
seed=self.seed,
|
||||
revision=self.revision,
|
||||
code_revision=self.code_revision,
|
||||
hf_token=self.hf_token,
|
||||
hf_overrides=self.hf_overrides,
|
||||
tokenizer_revision=self.tokenizer_revision,
|
||||
max_model_len=self.max_model_len,
|
||||
quantization=self.quantization,
|
||||
allow_deprecated_quantization=self.allow_deprecated_quantization,
|
||||
enforce_eager=self.enforce_eager,
|
||||
enable_return_routed_experts=self.enable_return_routed_experts,
|
||||
max_logprobs=self.max_logprobs,
|
||||
logprobs_mode=self.logprobs_mode,
|
||||
disable_sliding_window=self.disable_sliding_window,
|
||||
disable_cascade_attn=self.disable_cascade_attn,
|
||||
skip_tokenizer_init=self.skip_tokenizer_init,
|
||||
enable_prompt_embeds=self.enable_prompt_embeds,
|
||||
served_model_name=self.served_model_name,
|
||||
language_model_only=language_model_only,
|
||||
limit_mm_per_prompt=limit_mm_per_prompt,
|
||||
enable_mm_embeds=enable_mm_embeds,
|
||||
interleave_mm_strings=interleave_mm_strings,
|
||||
media_io_kwargs=media_io_kwargs,
|
||||
skip_mm_profiling=skip_mm_profiling,
|
||||
config_format=self.config_format,
|
||||
mm_processor_kwargs=mm_processor_kwargs,
|
||||
mm_processor_cache_gb=mm_processor_cache_gb,
|
||||
mm_processor_cache_type=mm_processor_cache_type,
|
||||
mm_shm_cache_max_object_size_mb=mm_shm_cache_max_object_size_mb,
|
||||
mm_encoder_only=mm_encoder_only,
|
||||
mm_encoder_tp_mode=mm_encoder_tp_mode,
|
||||
mm_encoder_attn_backend=mm_encoder_attn_backend,
|
||||
pooler_config=self.pooler_config,
|
||||
generation_config=self.generation_config,
|
||||
override_generation_config=self.override_generation_config,
|
||||
enable_sleep_mode=self.enable_sleep_mode,
|
||||
model_impl=self.model_impl,
|
||||
override_attention_dtype=self.override_attention_dtype,
|
||||
logits_processors=self.logits_processors,
|
||||
video_pruning_rate=video_pruning_rate,
|
||||
io_processor_plugin=self.io_processor_plugin,
|
||||
# Omni-specific fields
|
||||
stage_id=self.stage_id,
|
||||
async_chunk=self.async_chunk,
|
||||
model_stage=self.model_stage,
|
||||
model_arch=self.model_arch,
|
||||
worker_type=self.worker_type,
|
||||
engine_output_type=self.engine_output_type,
|
||||
hf_config_name=self.hf_config_name,
|
||||
custom_process_next_stage_input_func=self.custom_process_next_stage_input_func,
|
||||
stage_connector_config=stage_connector_config,
|
||||
omni_kv_config=self.omni_kv_config,
|
||||
task_type=self.task_type,
|
||||
)
|
||||
omni_config.hf_config.architectures = omni_config.architectures
|
||||
|
||||
return omni_config
|
||||
|
||||
|
||||
@dataclass
|
||||
class AsyncOmniEngineArgs(AsyncEngineArgs):
|
||||
"""Async engine arguments for omni models, extending base AsyncEngineArgs.
|
||||
Adds omni-specific configuration fields for multi-stage pipeline
|
||||
processing and output type specification in async contexts.
|
||||
Args:
|
||||
stage_id: Identifier for the stage in a multi-stage pipeline (default: 0)
|
||||
model_stage: Stage type identifier, e.g., "thinker" or "talker"
|
||||
(default: "thinker")
|
||||
model_arch: Model architecture name
|
||||
(default: "Qwen2_5OmniForConditionalGeneration")
|
||||
engine_output_type: Optional output type specification for the engine.
|
||||
Used to route outputs to appropriate processors (e.g., "image",
|
||||
"audio", "latents"). If None, output type is inferred.
|
||||
stage_connector_spec: Extra configuration for stage connector
|
||||
worker_type: Model Type, e.g., "ar" or "generation"
|
||||
task_type: Default task type for TTS models (CustomVoice, VoiceDesign, or Base).
|
||||
If not specified, will be inferred from model path.
|
||||
"""
|
||||
|
||||
stage_id: int = 0
|
||||
model_stage: str = "thinker"
|
||||
model_arch: str | None = None
|
||||
engine_output_type: str | None = None
|
||||
hf_config_name: str | None = None
|
||||
custom_process_next_stage_input_func: str | None = None
|
||||
stage_connector_spec: dict[str, Any] = field(default_factory=dict)
|
||||
async_chunk: bool = False
|
||||
omni_kv_config: dict | None = None
|
||||
quantization_config: Any | None = None
|
||||
worker_type: str | None = None
|
||||
task_type: str | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
load_omni_general_plugins()
|
||||
super().__post_init__()
|
||||
|
||||
def _ensure_omni_models_registered(self):
|
||||
if hasattr(self, "_omni_models_registered"):
|
||||
return True
|
||||
register_omni_models_to_vllm()
|
||||
self._omni_models_registered = True
|
||||
return True
|
||||
|
||||
def create_model_config(self) -> OmniModelConfig:
|
||||
"""Create an OmniModelConfig from these engine arguments.
|
||||
Returns:
|
||||
OmniModelConfig instance with all configuration fields set
|
||||
"""
|
||||
# GGUF files need a specific model loader path in vLLM.
|
||||
if is_gguf(self.model):
|
||||
self.quantization = self.load_format = "gguf"
|
||||
|
||||
if not envs.VLLM_ENABLE_V1_MULTIPROCESSING:
|
||||
logger.warning(
|
||||
"The global random seed is set to %d. Since "
|
||||
"VLLM_ENABLE_V1_MULTIPROCESSING is set to False, this may "
|
||||
"affect the random state of the Python process that "
|
||||
"launched vLLM.",
|
||||
self.seed,
|
||||
)
|
||||
|
||||
# register omni models to avoid model not found error
|
||||
self._ensure_omni_models_registered()
|
||||
|
||||
# Keep compatibility when async args are constructed from partial payloads.
|
||||
limit_mm_per_prompt = getattr(self, "limit_mm_per_prompt", {})
|
||||
language_model_only = getattr(self, "language_model_only", False)
|
||||
limit_mm_per_prompt = getattr(self, "limit_mm_per_prompt", {})
|
||||
enable_mm_embeds = getattr(self, "enable_mm_embeds", False)
|
||||
interleave_mm_strings = getattr(self, "interleave_mm_strings", False)
|
||||
media_io_kwargs = getattr(self, "media_io_kwargs", {})
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,300 +0,0 @@
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.inputs import ProcessorInputs, PromptType
|
||||
from vllm.inputs.parse import split_enc_dec_inputs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
|
||||
from vllm.multimodal.inputs import MultiModalFeatureSpec
|
||||
from vllm.multimodal.utils import argsort_mm_positions
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.renderers import BaseRenderer
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.tasks import SupportedTask
|
||||
from vllm.utils import length_from_prompt_token_ids_or_embeds
|
||||
from vllm.utils.jsontree import json_iter_leaves
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
|
||||
from vllm_omni.engine import (
|
||||
AdditionalInformationEntry,
|
||||
AdditionalInformationPayload,
|
||||
OmniEngineCoreRequest,
|
||||
PromptEmbedsPayload,
|
||||
)
|
||||
from vllm_omni.inputs.preprocess import OmniInputPreprocessor
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_OMNI_EXTRA_KEYS = (
|
||||
"additional_information",
|
||||
"prompt_embeds",
|
||||
"negative_prompt",
|
||||
"negative_prompt_embeds",
|
||||
)
|
||||
|
||||
|
||||
def reinject_omni_fields(
|
||||
results: list[ProcessorInputs],
|
||||
original_prompts: list[dict],
|
||||
) -> None:
|
||||
"""Re-inject omni-specific fields that the upstream renderer discards.
|
||||
|
||||
The upstream renderer's ``process_for_engine`` creates new dicts that only
|
||||
copy standard vLLM fields (prompt_token_ids, multi_modal_data, …).
|
||||
Omni-specific fields such as ``additional_information`` and
|
||||
``prompt_embeds`` are silently dropped. This helper copies them back from
|
||||
the *original* parsed prompts into the renderer outputs so they survive
|
||||
into ``OmniInputProcessor.process_inputs()``.
|
||||
"""
|
||||
for result, orig in zip(results, original_prompts):
|
||||
if not isinstance(orig, dict):
|
||||
continue
|
||||
for key in _OMNI_EXTRA_KEYS:
|
||||
val = orig.get(key)
|
||||
if val is not None and key not in result:
|
||||
result[key] = val
|
||||
|
||||
|
||||
class OmniInputProcessor(InputProcessor):
|
||||
"""Processor for omni models, handling multimodal inputs and embeddings.
|
||||
|
||||
Extends the base vLLM Processor with support for processing prompt
|
||||
embeddings and additional information payloads, enabling direct transfer
|
||||
of pre-computed embeddings between pipeline stages.
|
||||
|
||||
Args:
|
||||
vllm_config: Global vLLM configuration
|
||||
mm_registry: Multi-modal registry for processing multimodal inputs
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _dtype_to_name(dtype: torch.dtype) -> str:
|
||||
"""Convert torch dtype to string representation.
|
||||
|
||||
Args:
|
||||
dtype: PyTorch dtype to convert
|
||||
|
||||
Returns:
|
||||
String representation of the dtype (e.g., "float32", "int64")
|
||||
"""
|
||||
mapping = {
|
||||
torch.float32: "float32",
|
||||
torch.float: "float32",
|
||||
torch.float16: "float16",
|
||||
torch.half: "float16",
|
||||
torch.bfloat16: "bfloat16",
|
||||
torch.float64: "float64",
|
||||
torch.double: "float64",
|
||||
torch.int64: "int64",
|
||||
torch.long: "int64",
|
||||
torch.int32: "int32",
|
||||
torch.int: "int32",
|
||||
torch.int16: "int16",
|
||||
torch.short: "int16",
|
||||
torch.int8: "int8",
|
||||
torch.uint8: "uint8",
|
||||
torch.bool: "bool",
|
||||
}
|
||||
return mapping.get(dtype, str(dtype).replace("torch.", ""))
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
renderer: BaseRenderer | None = None,
|
||||
*,
|
||||
mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
|
||||
):
|
||||
super().__init__(vllm_config, renderer=renderer, mm_registry=mm_registry)
|
||||
self.input_preprocessor = OmniInputPreprocessor(
|
||||
vllm_config=vllm_config,
|
||||
renderer=self.renderer,
|
||||
mm_registry=mm_registry,
|
||||
)
|
||||
|
||||
def process_inputs(
|
||||
self,
|
||||
request_id: str,
|
||||
prompt: PromptType | ProcessorInputs,
|
||||
params: SamplingParams | PoolingParams,
|
||||
supported_tasks: tuple[SupportedTask, ...] = ("generate",),
|
||||
arrival_time: float | None = None,
|
||||
lora_request: LoRARequest | None = None,
|
||||
tokenization_kwargs: dict[str, Any] | None = None,
|
||||
trace_headers: Mapping[str, str] | None = None,
|
||||
priority: int = 0,
|
||||
data_parallel_rank: int | None = None,
|
||||
resumable: bool = False,
|
||||
) -> OmniEngineCoreRequest:
|
||||
"""Process input prompt into an engine core request.
|
||||
|
||||
Converts a prompt (text, tokens, or multimodal) into an
|
||||
OmniEngineCoreRequest that can be processed by the engine.
|
||||
Handles prompt embeddings and additional information payloads
|
||||
for direct transfer between stages.
|
||||
|
||||
Args:
|
||||
request_id: Unique identifier for this request
|
||||
prompt: Input prompt (text, token IDs, embeddings, or multimodal)
|
||||
params: Sampling or pooling parameters for generation
|
||||
supported_tasks: Tuple of supported tasks for validation
|
||||
arrival_time: Optional arrival timestamp (defaults to current time)
|
||||
lora_request: Optional LoRA adapter request
|
||||
tokenization_kwargs: Optional additional tokenization arguments
|
||||
trace_headers: Optional tracing headers for observability
|
||||
priority: Request priority (higher values processed first)
|
||||
data_parallel_rank: Optional data parallel rank for distributed
|
||||
inference
|
||||
resumable: Whether the request supports streaming input
|
||||
|
||||
Returns:
|
||||
OmniEngineCoreRequest ready for the engine
|
||||
|
||||
Raises:
|
||||
ValueError: If data_parallel_rank is out of range or prompt_embeds
|
||||
has incorrect shape
|
||||
"""
|
||||
self._validate_params(params, supported_tasks)
|
||||
self._validate_lora(lora_request)
|
||||
|
||||
parallel_config = self.vllm_config.parallel_config
|
||||
dp_size = parallel_config.data_parallel_size
|
||||
dp_local_size = parallel_config.data_parallel_size_local
|
||||
num_ranks = dp_local_size if parallel_config.local_engines_only else dp_size
|
||||
if data_parallel_rank is not None and not (0 <= data_parallel_rank < num_ranks):
|
||||
raise ValueError(f"data_parallel_rank {data_parallel_rank} is out of range [0, {num_ranks}).")
|
||||
|
||||
# Short-circuit for prompts already processed by the renderer
|
||||
# (they carry a "type" key). Raw prompts must still go through the
|
||||
# omni preprocessor which preserves additional_information, etc.
|
||||
if isinstance(prompt, dict) and "type" in prompt:
|
||||
if arrival_time is None:
|
||||
arrival_time = prompt.get("arrival_time", time.time())
|
||||
processed_inputs: ProcessorInputs = prompt # type: ignore[assignment]
|
||||
else:
|
||||
if arrival_time is None:
|
||||
arrival_time = time.time()
|
||||
|
||||
processed_inputs = self.input_preprocessor.preprocess(
|
||||
prompt,
|
||||
tokenization_kwargs=tokenization_kwargs,
|
||||
)
|
||||
|
||||
self._platform_validate_request(processed_inputs, params)
|
||||
|
||||
encoder_inputs, decoder_inputs = split_enc_dec_inputs(processed_inputs)
|
||||
self._validate_model_inputs(encoder_inputs, decoder_inputs)
|
||||
|
||||
# Normalize decoder prompt access across TypedDict variants.
|
||||
if decoder_inputs["type"] == "embeds":
|
||||
prompt_token_ids = None
|
||||
prompt_embeds = decoder_inputs["prompt_embeds"]
|
||||
else:
|
||||
prompt_token_ids = decoder_inputs["prompt_token_ids"]
|
||||
prompt_embeds = decoder_inputs.get("prompt_embeds")
|
||||
|
||||
sampling_params = None
|
||||
pooling_params = None
|
||||
if isinstance(params, SamplingParams):
|
||||
# TODO: can we avoid cloning here in multiproc case?
|
||||
sampling_params = params.clone()
|
||||
# If unset max tokens, then generate up to the max_model_len.
|
||||
if sampling_params.max_tokens is None:
|
||||
seq_len = length_from_prompt_token_ids_or_embeds(prompt_token_ids, prompt_embeds)
|
||||
sampling_params.max_tokens = self.model_config.max_model_len - seq_len
|
||||
sampling_params.update_from_generation_config(
|
||||
self.generation_config_fields,
|
||||
self.renderer.get_eos_token_id(),
|
||||
)
|
||||
if self.tokenizer is not None:
|
||||
sampling_params.update_from_tokenizer(self.tokenizer)
|
||||
else:
|
||||
pooling_params = params.clone()
|
||||
|
||||
# Multimodal related.
|
||||
mm_features: list[MultiModalFeatureSpec] | None = None
|
||||
|
||||
if decoder_inputs["type"] == "multimodal":
|
||||
decoder_mm_inputs = decoder_inputs["mm_kwargs"]
|
||||
decoder_mm_positions = decoder_inputs["mm_placeholders"]
|
||||
decoder_mm_hashes = decoder_inputs["mm_hashes"]
|
||||
|
||||
if not all(isinstance(leaf, str) for leaf in json_iter_leaves(decoder_mm_hashes)):
|
||||
raise ValueError(
|
||||
f"mm_hashes must contain only strings, got: {decoder_mm_hashes}. "
|
||||
"This is likely due to an incorrect custom implementation of "
|
||||
"MultiModalProcessor.apply method."
|
||||
)
|
||||
|
||||
# Merge and flatten multimodal placeholders, hashes and inputs
|
||||
# from dictionaries to lists, and sort them by each item's position
|
||||
# in the input sequence.
|
||||
sorted_mm_idxs = argsort_mm_positions(decoder_mm_positions)
|
||||
|
||||
mm_features = []
|
||||
for modality, idx in sorted_mm_idxs:
|
||||
base_mm_hash = decoder_mm_hashes[modality][idx]
|
||||
mm_features.append(
|
||||
MultiModalFeatureSpec(
|
||||
data=decoder_mm_inputs[modality][idx],
|
||||
modality=modality,
|
||||
identifier=self._get_mm_identifier(base_mm_hash, lora_request),
|
||||
mm_position=decoder_mm_positions[modality][idx],
|
||||
mm_hash=base_mm_hash,
|
||||
)
|
||||
)
|
||||
|
||||
# Compatibility: decode serialized prompt embeds if provided.
|
||||
if isinstance(prompt_embeds, PromptEmbedsPayload):
|
||||
prompt_embeds = self._decode_prompt_embeds(prompt_embeds)
|
||||
|
||||
additional_information_payload: AdditionalInformationPayload | None = None
|
||||
raw_info: dict[str, Any] | AdditionalInformationPayload | None = decoder_inputs.get("additional_information")
|
||||
if isinstance(raw_info, AdditionalInformationPayload):
|
||||
additional_information_payload = raw_info
|
||||
elif raw_info is not None:
|
||||
entries: dict[str, AdditionalInformationEntry] = {}
|
||||
for key, value in raw_info.items():
|
||||
if isinstance(value, torch.Tensor):
|
||||
v_cpu = value.detach().to("cpu").contiguous()
|
||||
dtype_str = self._dtype_to_name(v_cpu.dtype)
|
||||
data_bytes = v_cpu.numpy().tobytes()
|
||||
entry = AdditionalInformationEntry(
|
||||
tensor_data=data_bytes,
|
||||
tensor_shape=[int(x) for x in list(v_cpu.shape)],
|
||||
tensor_dtype=dtype_str,
|
||||
)
|
||||
elif isinstance(value, list):
|
||||
entry = AdditionalInformationEntry(list_data=value)
|
||||
else:
|
||||
raise ValueError("additional_information values must be Tensor or list")
|
||||
entries[key] = entry
|
||||
additional_information_payload = AdditionalInformationPayload(entries=entries)
|
||||
|
||||
return OmniEngineCoreRequest(
|
||||
request_id=request_id,
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
mm_features=mm_features,
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=pooling_params,
|
||||
arrival_time=arrival_time,
|
||||
lora_request=lora_request,
|
||||
cache_salt=decoder_inputs.get("cache_salt"),
|
||||
priority=priority,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
trace_headers=trace_headers,
|
||||
prompt_embeds=prompt_embeds,
|
||||
additional_information=additional_information_payload,
|
||||
resumable=resumable,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _decode_prompt_embeds(payload: PromptEmbedsPayload) -> torch.Tensor:
|
||||
dtype = getattr(np, payload.dtype)
|
||||
arr = np.frombuffer(payload.data, dtype=dtype)
|
||||
arr = arr.reshape(payload.shape)
|
||||
return torch.from_numpy(arr)
|
||||
@@ -0,0 +1,812 @@
|
||||
"""
|
||||
Orchestrator for vLLM-Omni multi-stage runtime.
|
||||
|
||||
Runs inside a background thread with its own asyncio event loop.
|
||||
Owns all StageEngineCoreClient instances, input/output processors,
|
||||
and handles stage-to-stage transfer logic.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import time as _time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import janus
|
||||
import torch
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.engine import EngineCoreOutputs
|
||||
|
||||
from vllm_omni.distributed.omni_connectors.adapter import compute_talker_prompt_ids_length
|
||||
from vllm_omni.engine import (
|
||||
OmniEngineCoreRequest,
|
||||
)
|
||||
from vllm_omni.engine.serialization import serialize_additional_information
|
||||
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
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def build_engine_core_request_from_tokens(
|
||||
request_id: str,
|
||||
prompt: dict[str, Any],
|
||||
params: SamplingParams | PoolingParams,
|
||||
arrival_time: float | None = None,
|
||||
model_config: ModelConfig | None = None,
|
||||
) -> OmniEngineCoreRequest:
|
||||
"""Build an OmniEngineCoreRequest directly from an OmniTokensPrompt.
|
||||
|
||||
Lightweight alternative to the full InputProcessor pipeline - skips
|
||||
tokenization, multimodal preprocessing, LoRA validation, and platform
|
||||
validation. Intended for stage 1+ where the upstream stage has already
|
||||
produced token IDs and optional embeddings.
|
||||
"""
|
||||
if arrival_time is None:
|
||||
arrival_time = _time.time()
|
||||
|
||||
prompt_token_ids = prompt["prompt_token_ids"]
|
||||
|
||||
# Clone params and set max_tokens if needed
|
||||
sampling_params = None
|
||||
pooling_params = None
|
||||
if isinstance(params, SamplingParams):
|
||||
sampling_params = params.clone()
|
||||
if sampling_params.max_tokens is None and model_config is not None:
|
||||
sampling_params.max_tokens = model_config.max_model_len - len(prompt_token_ids)
|
||||
else:
|
||||
pooling_params = params.clone()
|
||||
|
||||
prompt_embeds: torch.Tensor | None = prompt.get("prompt_embeds")
|
||||
|
||||
# Serialize additional_information if present
|
||||
additional_info_payload = serialize_additional_information(
|
||||
prompt.get("additional_information"),
|
||||
log_prefix=f"build_engine_core_request_from_tokens req={request_id}",
|
||||
)
|
||||
|
||||
return OmniEngineCoreRequest(
|
||||
request_id=request_id,
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
mm_features=None,
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=pooling_params,
|
||||
arrival_time=arrival_time,
|
||||
lora_request=None,
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
prompt_embeds=prompt_embeds,
|
||||
additional_information=additional_info_payload,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Orchestrator internals (run inside the background thread)
|
||||
# ============================================================
|
||||
|
||||
|
||||
@dataclass
|
||||
class OrchestratorRequestState:
|
||||
"""Per-request bookkeeping inside the Orchestrator."""
|
||||
|
||||
request_id: str
|
||||
prompt: Any = None
|
||||
sampling_params_list: list[Any] = field(default_factory=list)
|
||||
final_stage_id: int = -1
|
||||
|
||||
# Metrics: timestamp when request was submitted to each stage
|
||||
stage_submit_ts: dict[int, float] = field(default_factory=dict)
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
"""Runs inside a background thread's asyncio event loop.
|
||||
|
||||
Owns all StageEngineCoreClient instances, input/output processors,
|
||||
and handles stage-to-stage transfer logic.
|
||||
"""
|
||||
|
||||
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]],
|
||||
stage_clients: list[Any],
|
||||
output_processors: list[Any],
|
||||
stage_vllm_configs: list[Any],
|
||||
*,
|
||||
async_chunk: bool = False,
|
||||
) -> None:
|
||||
self.request_async_queue = request_async_queue
|
||||
self.output_async_queue = output_async_queue
|
||||
self.rpc_async_queue = rpc_async_queue
|
||||
|
||||
self.num_stages = len(stage_clients)
|
||||
self.async_chunk = bool(async_chunk)
|
||||
|
||||
self.stage_clients: list[Any] = stage_clients
|
||||
self.output_processors: list[Any] = output_processors
|
||||
self.stage_vllm_configs: list[Any] = stage_vllm_configs
|
||||
|
||||
# Per-request state
|
||||
self.request_states: dict[str, OrchestratorRequestState] = {}
|
||||
|
||||
# CFG companion tracking
|
||||
self._companion_map: dict[str, dict[str, str]] = {}
|
||||
self._companion_to_parent: dict[str, str] = {}
|
||||
self._companion_ids: set[str] = set()
|
||||
self._companion_done: dict[str, set[str]] = {}
|
||||
self._deferred_parents: dict[str, dict[str, Any]] = {}
|
||||
|
||||
# Per-stage metrics accumulators.
|
||||
self._batch_seq: list[int] = [0] * self.num_stages
|
||||
self._agg_total_tokens: list[int] = [0] * self.num_stages
|
||||
self._agg_total_gen_time_ms: list[float] = [0.0] * self.num_stages
|
||||
|
||||
# Shutdown coordination
|
||||
self._shutdown_event = asyncio.Event()
|
||||
self._stages_shutdown = False
|
||||
|
||||
async def run(self) -> None:
|
||||
"""Main entry point for the Orchestrator event loop."""
|
||||
logger.info("[Orchestrator] Starting event loop")
|
||||
|
||||
request_task = asyncio.create_task(self._request_handler(), name="orchestrator-request-handler")
|
||||
output_task = asyncio.create_task(
|
||||
self._orchestration_output_handler(),
|
||||
name="orchestrator-stage-output-handler",
|
||||
)
|
||||
|
||||
try:
|
||||
# Run both tasks concurrently; if either fails the other is cancelled.
|
||||
await asyncio.gather(request_task, output_task)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception("[Orchestrator] Fatal error in orchestrator tasks")
|
||||
raise
|
||||
finally:
|
||||
self._shutdown_event.set()
|
||||
for t in (request_task, output_task):
|
||||
if not t.done():
|
||||
t.cancel()
|
||||
try:
|
||||
await asyncio.gather(request_task, output_task, return_exceptions=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._shutdown_stages()
|
||||
|
||||
# Cancel any remaining tasks spawned by wait_for / gather so
|
||||
# the event loop can close cleanly without "pending task" errors.
|
||||
loop = asyncio.get_running_loop()
|
||||
pending = [t for t in asyncio.all_tasks(loop) if t is not asyncio.current_task() and not t.done()]
|
||||
for t in pending:
|
||||
t.cancel()
|
||||
if pending:
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
|
||||
async def _request_handler(self) -> None:
|
||||
"""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 == "add_companion_request":
|
||||
await self._handle_add_companion(msg)
|
||||
elif msg_type == "abort":
|
||||
await self._handle_abort(msg)
|
||||
elif msg_type == "collective_rpc":
|
||||
await self._handle_collective_rpc(msg)
|
||||
elif msg_type == "shutdown":
|
||||
logger.info("[Orchestrator] Received shutdown signal")
|
||||
self._shutdown_event.set()
|
||||
self._shutdown_stages()
|
||||
break
|
||||
else:
|
||||
logger.warning(f"[Orchestrator] Unknown message type: {msg_type}")
|
||||
|
||||
async def _orchestration_output_handler(self) -> None:
|
||||
"""Poll all stages, handle transfers, send final outputs to main."""
|
||||
try:
|
||||
await self._orchestration_loop()
|
||||
except asyncio.CancelledError:
|
||||
logger.debug("[Orchestrator] _orchestration_output_handler cancelled")
|
||||
return
|
||||
|
||||
async def _orchestration_loop(self) -> None:
|
||||
"""Inner loop for _orchestration_output_handler (clean cancellation).
|
||||
|
||||
Control flow: poll raw → process through output processor → route.
|
||||
"""
|
||||
while not self._shutdown_event.is_set():
|
||||
idle = True
|
||||
for stage_id in range(self.num_stages):
|
||||
if self._shutdown_event.is_set():
|
||||
return
|
||||
|
||||
# 1) Diffusion stage: poll non-blocking queue
|
||||
# TODO (Peiqi): the output of diffusion stage is OmniRequestOutput,
|
||||
# which is different from EngineCoreOutputs (LLM stages). We may want to unify
|
||||
# the output format in the future to simplify the processing logic in Orchestrator.
|
||||
stage_client = self.stage_clients[stage_id]
|
||||
if stage_client.stage_type == "diffusion":
|
||||
output = stage_client.get_diffusion_output_async()
|
||||
if output is not None:
|
||||
idle = False
|
||||
req_state = self.request_states.get(output.request_id)
|
||||
if req_state is not None:
|
||||
stage_metrics = self._build_stage_metrics(stage_id, output.request_id, [output], req_state)
|
||||
await self._route_output(stage_id, output, req_state, stage_metrics)
|
||||
continue
|
||||
|
||||
# 1) Poll raw outputs from the stage
|
||||
try:
|
||||
raw_outputs = await asyncio.wait_for(self._poll_stage_raw(stage_id), timeout=0.001)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
if self._shutdown_event.is_set():
|
||||
return
|
||||
logger.exception(
|
||||
"[Orchestrator] _poll_stage_raw failed for stage-%s",
|
||||
stage_id,
|
||||
)
|
||||
raise
|
||||
|
||||
if raw_outputs is None:
|
||||
continue
|
||||
idle = False
|
||||
|
||||
# 2) Process raw outputs through the output processor
|
||||
request_outputs = await self._process_stage_outputs(stage_id, raw_outputs)
|
||||
|
||||
# 3) Route each processed output
|
||||
for output in request_outputs:
|
||||
req_state = self.request_states.get(output.request_id)
|
||||
if req_state is None:
|
||||
logger.warning(
|
||||
"[Orchestrator] Dropping output for unknown req %s at stage-%s (known reqs: %s)",
|
||||
output.request_id,
|
||||
stage_id,
|
||||
list(self.request_states.keys()),
|
||||
)
|
||||
continue
|
||||
stage_metrics = None
|
||||
if output.finished:
|
||||
stage_metrics = self._build_stage_metrics(
|
||||
stage_id,
|
||||
output.request_id,
|
||||
[output],
|
||||
req_state,
|
||||
)
|
||||
await self._route_output(stage_id, output, req_state, stage_metrics)
|
||||
|
||||
if idle:
|
||||
await asyncio.sleep(0.001)
|
||||
else:
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def _route_output(
|
||||
self,
|
||||
stage_id: int,
|
||||
output: Any,
|
||||
req_state: OrchestratorRequestState,
|
||||
stage_metrics: Any,
|
||||
) -> None:
|
||||
"""Route a processed output: send to main thread and/or forward to next stage."""
|
||||
req_id = output.request_id
|
||||
finished = output.finished
|
||||
submit_ts = req_state.stage_submit_ts.get(stage_id)
|
||||
stage_client = self.stage_clients[stage_id]
|
||||
|
||||
# CFG companion handling: companions don't produce user-visible output
|
||||
# and don't forward to the next stage directly.
|
||||
if finished and req_id in self._companion_ids:
|
||||
parent_id = self._companion_to_parent.get(req_id)
|
||||
if parent_id is not None:
|
||||
self._companion_done.setdefault(parent_id, set()).add(req_id)
|
||||
logger.debug(
|
||||
"[Orchestrator] CFG companion %s done (parent=%s)",
|
||||
req_id,
|
||||
parent_id,
|
||||
)
|
||||
# Check if parent is waiting and all companions are done
|
||||
if parent_id in self._deferred_parents and self._all_companions_done(parent_id):
|
||||
deferred = self._deferred_parents.pop(parent_id)
|
||||
parent_state = self.request_states.get(parent_id)
|
||||
if parent_state is not None:
|
||||
await self._forward_to_next_stage(
|
||||
parent_id,
|
||||
deferred["stage_id"],
|
||||
deferred["output"],
|
||||
parent_state,
|
||||
)
|
||||
self.request_states.pop(req_id, None)
|
||||
return
|
||||
|
||||
if stage_client.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,
|
||||
}
|
||||
)
|
||||
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,
|
||||
}
|
||||
)
|
||||
|
||||
if finished and stage_id < req_state.final_stage_id and not self.async_chunk:
|
||||
# If this parent has CFG companions, defer forwarding until all done
|
||||
if req_id in self._companion_map and not self._all_companions_done(req_id):
|
||||
self._deferred_parents[req_id] = {
|
||||
"stage_id": stage_id,
|
||||
"output": output,
|
||||
}
|
||||
logger.debug(
|
||||
"[Orchestrator] Parent %s deferred, waiting for CFG companions",
|
||||
req_id,
|
||||
)
|
||||
else:
|
||||
await self._forward_to_next_stage(req_id, stage_id, output, req_state)
|
||||
|
||||
if finished and stage_id == req_state.final_stage_id:
|
||||
self._cleanup_companion_state(req_id)
|
||||
self.request_states.pop(req_id, None)
|
||||
|
||||
def _cleanup_companion_state(self, parent_id: str) -> None:
|
||||
"""Remove all companion tracking state for a completed parent."""
|
||||
role_map = self._companion_map.pop(parent_id, {})
|
||||
for cid in role_map.values():
|
||||
self._companion_ids.discard(cid)
|
||||
self._companion_to_parent.pop(cid, None)
|
||||
self._companion_done.pop(parent_id, None)
|
||||
self._deferred_parents.pop(parent_id, None)
|
||||
|
||||
def _all_companions_done(self, parent_id: str) -> bool:
|
||||
"""Check whether all CFG companions for a parent request have finished."""
|
||||
role_map = self._companion_map.get(parent_id, {})
|
||||
if not role_map:
|
||||
return True
|
||||
done_set = self._companion_done.get(parent_id, set())
|
||||
return all(cid in done_set for cid in role_map.values())
|
||||
|
||||
def _build_stage_metrics(
|
||||
self,
|
||||
stage_id: int,
|
||||
req_id: str,
|
||||
request_outputs: list[RequestOutput],
|
||||
req_state: OrchestratorRequestState,
|
||||
) -> StageRequestMetrics:
|
||||
"""Build StageRequestMetrics for a finished request at a stage.
|
||||
|
||||
Reuses StageRequestMetrics so OrchestratorMetrics and downstream
|
||||
metric handlers can consume a stable schema.
|
||||
"""
|
||||
now = _time.time()
|
||||
submit_ts = req_state.stage_submit_ts.get(stage_id, now)
|
||||
stage_gen_time_ms = (now - submit_ts) * 1000.0
|
||||
|
||||
num_tokens_out = count_tokens_from_outputs(request_outputs)
|
||||
num_tokens_in = 0
|
||||
if stage_id == 0:
|
||||
for ro in request_outputs:
|
||||
ptids = getattr(ro, "prompt_token_ids", None)
|
||||
if ptids is not None:
|
||||
num_tokens_in += len(ptids)
|
||||
|
||||
# Monotonic batch counter per stage.
|
||||
self._batch_seq[stage_id] += 1
|
||||
batch_id = self._batch_seq[stage_id]
|
||||
|
||||
# Accumulate for running-average stage_stats
|
||||
self._agg_total_tokens[stage_id] += num_tokens_out
|
||||
self._agg_total_gen_time_ms[stage_id] += stage_gen_time_ms
|
||||
|
||||
return StageRequestMetrics(
|
||||
num_tokens_in=num_tokens_in,
|
||||
num_tokens_out=num_tokens_out,
|
||||
stage_gen_time_ms=stage_gen_time_ms,
|
||||
batch_id=batch_id,
|
||||
batch_size=1,
|
||||
rx_decode_time_ms=0.0,
|
||||
rx_transfer_bytes=0,
|
||||
rx_in_flight_time_ms=0.0,
|
||||
stage_stats=StageStats(
|
||||
total_token=self._agg_total_tokens[stage_id],
|
||||
total_gen_time_ms=self._agg_total_gen_time_ms[stage_id],
|
||||
),
|
||||
)
|
||||
|
||||
async def _forward_to_next_stage(
|
||||
self,
|
||||
req_id: str,
|
||||
stage_id: int,
|
||||
output: Any,
|
||||
req_state: OrchestratorRequestState,
|
||||
) -> None:
|
||||
"""Forward output from current stage to the next stage.
|
||||
|
||||
Handles the full pipeline: set outputs on current stage, compute
|
||||
next-stage inputs, build lightweight requests, and submit them.
|
||||
"""
|
||||
next_stage_id = stage_id + 1
|
||||
next_client = self.stage_clients[next_stage_id]
|
||||
params = req_state.sampling_params_list[next_stage_id]
|
||||
|
||||
if next_client.stage_type == "diffusion":
|
||||
self.stage_clients[stage_id].set_engine_outputs([output])
|
||||
if next_client.custom_process_input_func is not None:
|
||||
diffusion_prompt = next_client.custom_process_input_func(
|
||||
self.stage_clients,
|
||||
next_client.engine_input_source,
|
||||
req_state.prompt,
|
||||
False,
|
||||
)
|
||||
if isinstance(diffusion_prompt, list):
|
||||
diffusion_prompt = diffusion_prompt[0]
|
||||
else:
|
||||
diffusion_prompt = req_state.prompt
|
||||
|
||||
# Attach CFG companion KV request IDs so the diffusion model
|
||||
# runner can fetch companion KV caches alongside the primary one.
|
||||
cfg_ids = self._companion_map.get(req_id)
|
||||
if cfg_ids:
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
if isinstance(params, OmniDiffusionSamplingParams):
|
||||
params = copy.deepcopy(params)
|
||||
params.cfg_kv_request_ids = cfg_ids
|
||||
logger.info(
|
||||
"[Orchestrator] Attaching cfg_kv_request_ids=%s to req %s",
|
||||
cfg_ids,
|
||||
req_id,
|
||||
)
|
||||
|
||||
await next_client.add_request_async(req_id, diffusion_prompt, params)
|
||||
req_state.stage_submit_ts[next_stage_id] = _time.time()
|
||||
return
|
||||
|
||||
self.stage_clients[stage_id].set_engine_outputs([output])
|
||||
|
||||
# Process inputs for next stage
|
||||
try:
|
||||
next_inputs = next_client.process_engine_inputs(
|
||||
stage_list=self.stage_clients,
|
||||
prompt=req_state.prompt,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"[Orchestrator] req=%s process_engine_inputs FAILED for stage-%s",
|
||||
req_id,
|
||||
next_stage_id,
|
||||
)
|
||||
raise
|
||||
|
||||
# Build and submit requests for each input
|
||||
for next_input in next_inputs:
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=req_id,
|
||||
prompt=next_input,
|
||||
params=params,
|
||||
model_config=self.stage_vllm_configs[next_stage_id].model_config,
|
||||
)
|
||||
|
||||
# TODO: Here we directly use the req id to assign.
|
||||
request.external_req_id = request.request_id
|
||||
|
||||
self.output_processors[next_stage_id].add_request(
|
||||
request=request,
|
||||
prompt=None,
|
||||
parent_req=None,
|
||||
request_index=0,
|
||||
queue=None,
|
||||
)
|
||||
|
||||
await next_client.add_request_async(request)
|
||||
|
||||
# Record submit timestamp for the next stage
|
||||
req_state.stage_submit_ts[next_stage_id] = _time.time()
|
||||
|
||||
async def _poll_stage_raw(self, stage_id: int) -> EngineCoreOutputs | None:
|
||||
"""Pull raw EngineCoreOutputs from a stage client without processing.
|
||||
|
||||
Returns the raw outputs object, or None when there is nothing
|
||||
to consume.
|
||||
"""
|
||||
outputs = await self.stage_clients[stage_id].get_output_async()
|
||||
if not outputs.outputs:
|
||||
return None
|
||||
return outputs
|
||||
|
||||
async def _process_stage_outputs(self, stage_id: int, raw_outputs: EngineCoreOutputs) -> list[RequestOutput]:
|
||||
"""Run the output processor on raw outputs, returning RequestOutputs.
|
||||
|
||||
Also handles abort forwarding and scheduler stats updates.
|
||||
"""
|
||||
processor = self.output_processors[stage_id]
|
||||
|
||||
processed = processor.process_outputs(
|
||||
raw_outputs.outputs,
|
||||
raw_outputs.timestamp,
|
||||
None,
|
||||
)
|
||||
|
||||
if processed.reqs_to_abort:
|
||||
await self.stage_clients[stage_id].abort_requests_async(processed.reqs_to_abort)
|
||||
|
||||
if raw_outputs.scheduler_stats is not None:
|
||||
processor.update_scheduler_stats(raw_outputs.scheduler_stats)
|
||||
|
||||
return processed.request_outputs
|
||||
|
||||
async def _handle_add_request(self, msg: dict[str, Any]) -> 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"]
|
||||
if not sampling_params_list:
|
||||
raise ValueError(f"Missing sampling params for stage 0. Got {len(sampling_params_list)} stage params.")
|
||||
params = sampling_params_list[0]
|
||||
final_stage_id = msg["final_stage_id"]
|
||||
|
||||
logger.info(
|
||||
"[Orchestrator] _handle_add_request: stage=%s req=%s "
|
||||
"prompt_type=%s original_prompt_type=%s final_stage=%s "
|
||||
"num_sampling_params=%d",
|
||||
stage_id,
|
||||
request_id,
|
||||
type(prompt).__name__,
|
||||
type(original_prompt).__name__,
|
||||
final_stage_id,
|
||||
len(sampling_params_list),
|
||||
)
|
||||
|
||||
# Track request state - use original_prompt so downstream stages
|
||||
# (e.g. thinker2talker) can access the raw dict with multi_modal_data.
|
||||
req_state = OrchestratorRequestState(
|
||||
request_id=request_id,
|
||||
prompt=original_prompt,
|
||||
sampling_params_list=sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
)
|
||||
req_state.stage_submit_ts[stage_id] = _time.time()
|
||||
self.request_states[request_id] = req_state
|
||||
|
||||
# Stage-0 prompt is already a fully-formed OmniEngineCoreRequest
|
||||
# (pre-processed by AsyncOmniEngine.add_request, output processor
|
||||
# already registered there) - submit directly.
|
||||
request = prompt
|
||||
stage_client = self.stage_clients[stage_id]
|
||||
if stage_client.stage_type == "diffusion":
|
||||
await stage_client.add_request_async(request_id, prompt, params)
|
||||
else:
|
||||
await stage_client.add_request_async(request)
|
||||
|
||||
if self.async_chunk and stage_id == 0 and final_stage_id > 0:
|
||||
await self._prewarm_async_chunk_stages(request_id, request, req_state)
|
||||
|
||||
async def _prewarm_async_chunk_stages(
|
||||
self,
|
||||
request_id: str,
|
||||
stage0_request: Any,
|
||||
req_state: OrchestratorRequestState,
|
||||
) -> None:
|
||||
"""Pre-submit downstream stages for async-chunk mode.
|
||||
|
||||
In async-chunk mode, stages exchange data through connectors/chunk adapters,
|
||||
so downstream stages should be armed once at request start instead of waiting
|
||||
for stage-finished forwarding.
|
||||
"""
|
||||
if req_state.final_stage_id <= 0:
|
||||
return
|
||||
|
||||
prompt_token_ids = getattr(stage0_request, "prompt_token_ids", None)
|
||||
if prompt_token_ids is None:
|
||||
logger.warning(
|
||||
"[Orchestrator] async_chunk prewarm skipped for req=%s: stage0 prompt_token_ids missing",
|
||||
request_id,
|
||||
)
|
||||
return
|
||||
|
||||
# Pre-arm stage-1+ with placeholder prompt IDs.
|
||||
try:
|
||||
next_prompt_len = max(1, compute_talker_prompt_ids_length(prompt_token_ids))
|
||||
except Exception:
|
||||
next_prompt_len = max(1, len(prompt_token_ids))
|
||||
original_prompt = req_state.prompt
|
||||
if isinstance(original_prompt, dict):
|
||||
base_input = copy.deepcopy(original_prompt)
|
||||
else:
|
||||
base_input = {}
|
||||
base_input["prompt_token_ids"] = [0] * next_prompt_len
|
||||
base_input["multi_modal_data"] = None
|
||||
base_input["mm_processor_kwargs"] = None
|
||||
|
||||
for next_stage_id in range(1, req_state.final_stage_id + 1):
|
||||
next_client = self.stage_clients[next_stage_id]
|
||||
params = req_state.sampling_params_list[next_stage_id]
|
||||
|
||||
if next_client.stage_type == "diffusion":
|
||||
await next_client.add_request_async(request_id, req_state.prompt, params)
|
||||
req_state.stage_submit_ts[next_stage_id] = _time.time()
|
||||
continue
|
||||
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=request_id,
|
||||
prompt=base_input,
|
||||
params=params,
|
||||
model_config=self.stage_vllm_configs[next_stage_id].model_config,
|
||||
)
|
||||
request.external_req_id = request.request_id
|
||||
|
||||
self.output_processors[next_stage_id].add_request(
|
||||
request=request,
|
||||
prompt=None,
|
||||
parent_req=None,
|
||||
request_index=0,
|
||||
queue=None,
|
||||
)
|
||||
await next_client.add_request_async(request)
|
||||
req_state.stage_submit_ts[next_stage_id] = _time.time()
|
||||
|
||||
async def _handle_add_companion(self, msg: dict[str, Any]) -> 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"]
|
||||
|
||||
# Register companion mapping
|
||||
if parent_id not in self._companion_map:
|
||||
self._companion_map[parent_id] = {}
|
||||
self._companion_map[parent_id][role] = companion_id
|
||||
self._companion_ids.add(companion_id)
|
||||
self._companion_to_parent[companion_id] = parent_id
|
||||
self._companion_done.setdefault(parent_id, set())
|
||||
|
||||
companion_state = OrchestratorRequestState(
|
||||
request_id=companion_id,
|
||||
prompt=companion_prompt,
|
||||
sampling_params_list=sampling_params_list,
|
||||
final_stage_id=0,
|
||||
)
|
||||
companion_state.stage_submit_ts[0] = _time.time()
|
||||
self.request_states[companion_id] = companion_state
|
||||
|
||||
request = companion_prompt # Already a processed OmniEngineCoreRequest
|
||||
stage_client = self.stage_clients[0]
|
||||
await stage_client.add_request_async(request)
|
||||
|
||||
logger.info(
|
||||
"[Orchestrator] CFG companion submitted: %s (role=%s, parent=%s)",
|
||||
companion_id,
|
||||
role,
|
||||
parent_id,
|
||||
)
|
||||
|
||||
async def _handle_abort(self, msg: dict[str, Any]) -> None:
|
||||
"""Handle an abort message from the main thread."""
|
||||
request_ids = msg["request_ids"]
|
||||
# Also abort any CFG companions for aborted parents
|
||||
companion_ids_to_abort: list[str] = []
|
||||
for req_id in request_ids:
|
||||
role_map = self._companion_map.pop(req_id, {})
|
||||
for cid in role_map.values():
|
||||
companion_ids_to_abort.append(cid)
|
||||
self._companion_ids.discard(cid)
|
||||
self._companion_to_parent.pop(cid, None)
|
||||
self.request_states.pop(cid, None)
|
||||
self._companion_done.pop(req_id, None)
|
||||
self._deferred_parents.pop(req_id, None)
|
||||
|
||||
all_ids_to_abort = list(request_ids) + companion_ids_to_abort
|
||||
for stage_id in range(self.num_stages):
|
||||
await self.stage_clients[stage_id].abort_requests_async(all_ids_to_abort)
|
||||
for req_id in request_ids:
|
||||
self.request_states.pop(req_id, None)
|
||||
logger.info("[Orchestrator] Aborted request(s) %s", request_ids)
|
||||
|
||||
async def _handle_collective_rpc(self, msg: dict[str, Any]) -> None:
|
||||
"""Handle a control-plane RPC request from the main thread.
|
||||
|
||||
TODO(AsyncOmni): parallelize stage dispatch if control latency becomes
|
||||
noticeable. The current sequential fanout keeps the first version simple
|
||||
and deterministic.
|
||||
"""
|
||||
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")
|
||||
stage_ids = list(range(self.num_stages)) if requested_stage_ids is None else list(requested_stage_ids)
|
||||
|
||||
results: list[Any] = []
|
||||
for stage_id in stage_ids:
|
||||
if stage_id < 0 or stage_id >= self.num_stages:
|
||||
results.append(
|
||||
{
|
||||
"supported": False,
|
||||
"todo": True,
|
||||
"error": f"Invalid stage id {stage_id}",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
stage_client = self.stage_clients[stage_id]
|
||||
try:
|
||||
if hasattr(stage_client, "collective_rpc_async"):
|
||||
stage_result = await stage_client.collective_rpc_async(
|
||||
method=method,
|
||||
timeout=timeout,
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
else:
|
||||
stage_result = {
|
||||
"supported": False,
|
||||
"todo": True,
|
||||
"reason": (f"{stage_client.__class__.__name__}.collective_rpc_async is not implemented yet"),
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.exception(
|
||||
"[Orchestrator] collective_rpc failed: stage=%s method=%s",
|
||||
stage_id,
|
||||
method,
|
||||
)
|
||||
stage_result = {
|
||||
"supported": False,
|
||||
"error": str(exc),
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
)
|
||||
|
||||
def _shutdown_stages(self) -> None:
|
||||
"""Shutdown all stage clients."""
|
||||
if self._stages_shutdown:
|
||||
return
|
||||
|
||||
self._stages_shutdown = True
|
||||
logger.info("[Orchestrator] Shutting down all stages")
|
||||
for stage_id, stage_client in enumerate(self.stage_clients):
|
||||
try:
|
||||
stage_client.shutdown()
|
||||
logger.info(f"[Orchestrator] Stage {stage_id} shut down")
|
||||
except Exception as e:
|
||||
logger.warning(f"[Orchestrator] Failed to shutdown stage {stage_id}: {e}")
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Shared serialization helpers for omni engine request payloads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.engine import (
|
||||
AdditionalInformationEntry,
|
||||
AdditionalInformationPayload,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def dtype_to_name(dtype: torch.dtype) -> str:
|
||||
"""Convert torch dtype to a stable string name for serialization."""
|
||||
mapping = {
|
||||
torch.float32: "float32",
|
||||
torch.float: "float32",
|
||||
torch.float16: "float16",
|
||||
torch.half: "float16",
|
||||
torch.bfloat16: "bfloat16",
|
||||
torch.float64: "float64",
|
||||
torch.double: "float64",
|
||||
torch.int64: "int64",
|
||||
torch.long: "int64",
|
||||
torch.int32: "int32",
|
||||
torch.int: "int32",
|
||||
torch.int16: "int16",
|
||||
torch.short: "int16",
|
||||
torch.int8: "int8",
|
||||
torch.uint8: "uint8",
|
||||
torch.bool: "bool",
|
||||
}
|
||||
return mapping.get(dtype, str(dtype).replace("torch.", ""))
|
||||
|
||||
|
||||
def serialize_additional_information(
|
||||
raw_info: dict[str, Any] | AdditionalInformationPayload | None,
|
||||
*,
|
||||
log_prefix: str | None = None,
|
||||
) -> AdditionalInformationPayload | None:
|
||||
"""Serialize omni request metadata for EngineCore transport."""
|
||||
if raw_info is None:
|
||||
return None
|
||||
if isinstance(raw_info, AdditionalInformationPayload):
|
||||
return raw_info
|
||||
|
||||
entries: dict[str, AdditionalInformationEntry] = {}
|
||||
for key, value in raw_info.items():
|
||||
if isinstance(value, torch.Tensor):
|
||||
value_cpu = value.detach().to("cpu").contiguous()
|
||||
entries[key] = AdditionalInformationEntry(
|
||||
tensor_data=value_cpu.numpy().tobytes(),
|
||||
tensor_shape=list(value_cpu.shape),
|
||||
tensor_dtype=dtype_to_name(value_cpu.dtype),
|
||||
)
|
||||
continue
|
||||
|
||||
if isinstance(value, list):
|
||||
entries[key] = AdditionalInformationEntry(list_data=value)
|
||||
continue
|
||||
|
||||
if log_prefix is None:
|
||||
logger.warning(
|
||||
"Dropping unsupported additional_information key=%s type=%s",
|
||||
key,
|
||||
type(value).__name__,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"[%s] Dropping unsupported additional_information key=%s type=%s",
|
||||
log_prefix,
|
||||
key,
|
||||
type(value).__name__,
|
||||
)
|
||||
|
||||
return AdditionalInformationPayload(entries=entries) if entries else None
|
||||
@@ -0,0 +1,168 @@
|
||||
"""
|
||||
Stage Engine Core Client for vLLM-Omni multi-stage runtime.
|
||||
|
||||
Directly inherits from vLLM's AsyncMPClient to reuse EngineCore architecture.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.core_client import AsyncMPClient
|
||||
|
||||
from vllm_omni.engine.stage_init_utils import StageMetadata
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.engine import EngineCoreOutput
|
||||
|
||||
from vllm_omni.inputs.data import OmniTokensPrompt
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class StageEngineCoreClient(AsyncMPClient):
|
||||
"""Stage async client that inherits from vLLM's AsyncMPClient.
|
||||
|
||||
Fully reuses AsyncMPClient.__init__ for:
|
||||
- ZMQ setup, sockets
|
||||
- launch_core_engines() -> EngineCoreProc
|
||||
- outputs_queue, output_queue_task
|
||||
- All utility methods (shutdown, get_output_async, abort_requests_async, etc.)
|
||||
|
||||
This is the async version of StageMPClient, designed for use with AsyncOmniEngine.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: Any,
|
||||
executor_class: type,
|
||||
metadata: StageMetadata,
|
||||
client_addresses: dict[str, str] | None = None,
|
||||
engine_manager: Any = None,
|
||||
coordinator: Any = None,
|
||||
):
|
||||
"""Create an async EngineCore client for a single stage.
|
||||
|
||||
All heavy init (config extraction, plugin loading, device setup,
|
||||
engine args building, device locking) is done by the Orchestrator
|
||||
via helpers in stage_init_utils.py. This constructor just stores metadata
|
||||
and calls super().__init__().
|
||||
"""
|
||||
# -------- Stage metadata (public fields used at runtime) --------
|
||||
self.stage_id = metadata.stage_id
|
||||
self.stage_type = metadata.stage_type
|
||||
self.engine_output_type = metadata.engine_output_type
|
||||
self.is_comprehension = metadata.is_comprehension
|
||||
self.requires_multimodal_data = metadata.requires_multimodal_data
|
||||
self.engine_input_source = metadata.engine_input_source
|
||||
self.final_output = metadata.final_output
|
||||
self.final_output_type = metadata.final_output_type
|
||||
self.default_sampling_params = metadata.default_sampling_params
|
||||
self.custom_process_input_func = metadata.custom_process_input_func
|
||||
self.model_stage = metadata.model_stage
|
||||
|
||||
self.engine_outputs: Any = None
|
||||
|
||||
logger.info(
|
||||
"[StageEngineCoreClient] Stage-%s initializing EngineCore",
|
||||
self.stage_id,
|
||||
)
|
||||
try:
|
||||
super().__init__(
|
||||
vllm_config,
|
||||
executor_class,
|
||||
log_stats=False,
|
||||
client_addresses=client_addresses,
|
||||
)
|
||||
if engine_manager is not None:
|
||||
self.resources.engine_manager = engine_manager
|
||||
if coordinator is not None:
|
||||
self.resources.coordinator = coordinator
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"[StageEngineCoreClient] Stage-%s EngineCore init failed",
|
||||
self.stage_id,
|
||||
)
|
||||
try:
|
||||
self.shutdown()
|
||||
except Exception as shutdown_error:
|
||||
logger.warning(
|
||||
"[StageEngineCoreClient] Stage-%s cleanup after init failure failed: %s",
|
||||
self.stage_id,
|
||||
shutdown_error,
|
||||
)
|
||||
raise
|
||||
logger.info(
|
||||
"[StageEngineCoreClient] Stage-%s EngineCore running",
|
||||
self.stage_id,
|
||||
)
|
||||
|
||||
# ==================== Overrides ====================
|
||||
|
||||
async def add_request_async(self, request: EngineCoreRequest) -> None:
|
||||
"""Add request to the stage engine core."""
|
||||
logger.info(f"[StageEngineCoreClient] Stage-{self.stage_id} adding request: {request.request_id}")
|
||||
await super().add_request_async(request)
|
||||
|
||||
# ==================== Stage Methods ====================
|
||||
|
||||
def set_engine_outputs(self, engine_outputs: EngineCoreOutput) -> None:
|
||||
"""Set engine outputs (called by orchestrator)."""
|
||||
self.engine_outputs = engine_outputs
|
||||
|
||||
def process_engine_inputs(
|
||||
self,
|
||||
stage_list: list[Any],
|
||||
prompt: OmniTokensPrompt | list[OmniTokensPrompt] | None = None,
|
||||
) -> list[OmniTokensPrompt]:
|
||||
"""Process inputs from upstream stages."""
|
||||
from vllm_omni.inputs.data import OmniTokensPrompt
|
||||
|
||||
if self.custom_process_input_func is not None:
|
||||
return self.custom_process_input_func(
|
||||
stage_list,
|
||||
self.engine_input_source,
|
||||
prompt,
|
||||
self.requires_multimodal_data,
|
||||
)
|
||||
|
||||
if not self.engine_input_source:
|
||||
raise ValueError(f"engine_input_source empty for stage {self.stage_id}")
|
||||
|
||||
source_id = self.engine_input_source[0]
|
||||
source_outputs = stage_list[source_id].engine_outputs
|
||||
|
||||
if not isinstance(prompt, list):
|
||||
prompt = [prompt]
|
||||
|
||||
mm_data = {so.request_id: p.get("multi_modal_data") for so, p in zip(source_outputs, prompt)}
|
||||
|
||||
return [
|
||||
OmniTokensPrompt(
|
||||
prompt_token_ids=so.outputs[0].token_ids,
|
||||
multi_modal_data=(mm_data[so.request_id] if self.requires_multimodal_data else None),
|
||||
)
|
||||
for so in source_outputs
|
||||
]
|
||||
|
||||
async def collective_rpc_async(
|
||||
self,
|
||||
method: str,
|
||||
timeout: float | None = None,
|
||||
args: tuple[Any, ...] = (),
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
) -> Any:
|
||||
"""Forward control RPCs to the underlying AsyncMPClient stage engine.
|
||||
|
||||
Each ``StageEngineCoreClient`` already represents one logical stage, so
|
||||
stage-scoped control operations should be executed here and then fanned
|
||||
in-core across the workers managed by this EngineCore client.
|
||||
"""
|
||||
return await super().collective_rpc_async(
|
||||
method=method,
|
||||
timeout=timeout,
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
@@ -0,0 +1,525 @@
|
||||
"""
|
||||
Stage initialization helpers for vLLM-Omni multi-stage runtime.
|
||||
|
||||
Extracts orchestration-level init logic (config extraction, plugin loading,
|
||||
multiprocessing setup, device mapping, device locking, engine args building)
|
||||
out of StageEngineCoreClient into reusable functions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import importlib
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.usage.usage_lib import UsageContext
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
from vllm.v1.executor import Executor
|
||||
|
||||
from vllm_omni.engine.arg_utils import OmniEngineArgs
|
||||
from vllm_omni.entrypoints.stage_utils import _to_dict, set_stage_devices
|
||||
from vllm_omni.entrypoints.utils import filter_dataclass_kwargs, resolve_model_config_path
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParams
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _resolve_model_to_local_path(model: str) -> str:
|
||||
"""Resolve an HF Hub model ID to a local cache path."""
|
||||
if os.path.isdir(model):
|
||||
return model
|
||||
|
||||
try:
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
# Keep init path resolution offline-friendly.
|
||||
return snapshot_download(model, local_files_only=True)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"[stage_init] Could not resolve %s to local snapshot; using as-is",
|
||||
model,
|
||||
)
|
||||
return model
|
||||
|
||||
|
||||
def _resolve_model_tokenizer_paths(model: str, engine_args: dict[str, Any]) -> str:
|
||||
"""Apply model_subdir/tokenizer_subdir indirections from stage engine args."""
|
||||
model_subdir = engine_args.pop("model_subdir", None)
|
||||
tokenizer_subdir = engine_args.pop("tokenizer_subdir", None)
|
||||
if model_subdir is None and tokenizer_subdir is None:
|
||||
return model
|
||||
|
||||
resolved_base = _resolve_model_to_local_path(model)
|
||||
|
||||
if model_subdir:
|
||||
model = os.path.join(resolved_base, model_subdir)
|
||||
logger.info("[stage_init] Using model subdirectory: %s", 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("[stage_init] Using tokenizer from: %s", tokenizer_path)
|
||||
elif model_subdir and "tokenizer" not in engine_args:
|
||||
# Keep legacy behavior: model in subdir, tokenizer defaults to base path.
|
||||
engine_args["tokenizer"] = resolved_base
|
||||
logger.info("[stage_init] Using tokenizer from base model path: %s", resolved_base)
|
||||
|
||||
return model
|
||||
|
||||
|
||||
def resolve_worker_cls(engine_args: dict[str, Any]) -> None:
|
||||
"""Resolve worker_cls from worker_type for non-diffusion stages."""
|
||||
worker_type = engine_args.get("worker_type", None)
|
||||
if not worker_type:
|
||||
return
|
||||
worker_cls = engine_args.get("worker_cls")
|
||||
if worker_cls is not None and worker_cls != "auto":
|
||||
return
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
worker_type = str(worker_type).lower()
|
||||
if worker_type == "ar":
|
||||
engine_args["worker_cls"] = current_omni_platform.get_omni_ar_worker_cls()
|
||||
elif worker_type == "generation":
|
||||
engine_args["worker_cls"] = current_omni_platform.get_omni_generation_worker_cls()
|
||||
else:
|
||||
raise ValueError(f"Unknown worker_type: {worker_type}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class StageMetadata:
|
||||
"""Lightweight stage attributes extracted from stage_config."""
|
||||
|
||||
stage_id: int
|
||||
stage_type: Literal["llm", "diffusion"]
|
||||
engine_output_type: str | None
|
||||
is_comprehension: bool
|
||||
requires_multimodal_data: bool
|
||||
engine_input_source: list[int]
|
||||
final_output: bool
|
||||
final_output_type: str | None
|
||||
default_sampling_params: OmniSamplingParams
|
||||
custom_process_input_func: Callable | None
|
||||
model_stage: str | None
|
||||
runtime_cfg: Any
|
||||
prompt_expand_func: Callable | None = None
|
||||
cfg_kv_collect_func: Callable | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class StartedLlmStage:
|
||||
"""Resources for an LLM stage that has completed startup."""
|
||||
|
||||
stage_id: int
|
||||
metadata: Any
|
||||
vllm_config: Any
|
||||
executor_class: type
|
||||
engine_manager: Any
|
||||
coordinator: Any
|
||||
addresses: Any
|
||||
|
||||
|
||||
def extract_stage_metadata(stage_config: Any) -> StageMetadata:
|
||||
"""Pure data extraction from a stage_config object."""
|
||||
stage_id: int = stage_config.stage_id
|
||||
stage_type: Literal["llm", "diffusion"] = getattr(stage_config, "stage_type", "llm")
|
||||
engine_args = stage_config.engine_args
|
||||
runtime_cfg = getattr(stage_config, "runtime", {})
|
||||
engine_input_source: list[int] = getattr(stage_config, "engine_input_source", [])
|
||||
final_output: bool = getattr(stage_config, "final_output", False)
|
||||
final_output_type: str | None = getattr(stage_config, "final_output_type", None)
|
||||
|
||||
default_sp = _to_dict(getattr(stage_config, "default_sampling_params", {}))
|
||||
SPClass = SamplingParams if stage_type == "llm" else OmniDiffusionSamplingParams
|
||||
default_sampling_params: OmniSamplingParams = SPClass(**default_sp)
|
||||
|
||||
custom_process_input_func: Callable | None = None
|
||||
if hasattr(stage_config, "custom_process_input_func"):
|
||||
mod_path, fn_name = stage_config.custom_process_input_func.rsplit(".", 1)
|
||||
custom_process_input_func = getattr(importlib.import_module(mod_path), fn_name)
|
||||
|
||||
prompt_expand_func: Callable | None = None
|
||||
_pef_path = getattr(stage_config, "prompt_expand_func", None)
|
||||
if _pef_path:
|
||||
_mod, _fn = _pef_path.rsplit(".", 1)
|
||||
prompt_expand_func = getattr(importlib.import_module(_mod), _fn)
|
||||
|
||||
cfg_kv_collect_func: Callable | None = None
|
||||
_ckf_path = getattr(stage_config, "cfg_kv_collect_func", None)
|
||||
if _ckf_path:
|
||||
_mod, _fn = _ckf_path.rsplit(".", 1)
|
||||
cfg_kv_collect_func = getattr(importlib.import_module(_mod), _fn)
|
||||
|
||||
if stage_type == "diffusion":
|
||||
return StageMetadata(
|
||||
stage_id=stage_id,
|
||||
stage_type="diffusion",
|
||||
engine_output_type=None,
|
||||
is_comprehension=False,
|
||||
requires_multimodal_data=False,
|
||||
engine_input_source=engine_input_source,
|
||||
final_output=final_output,
|
||||
final_output_type=final_output_type,
|
||||
default_sampling_params=default_sampling_params,
|
||||
custom_process_input_func=custom_process_input_func,
|
||||
model_stage=None,
|
||||
runtime_cfg=runtime_cfg,
|
||||
cfg_kv_collect_func=cfg_kv_collect_func,
|
||||
)
|
||||
|
||||
model_stage = getattr(engine_args, "model_stage", None)
|
||||
engine_output_type = getattr(engine_args, "engine_output_type", None)
|
||||
is_comprehension = getattr(stage_config, "is_comprehension", False)
|
||||
requires_multimodal_data = getattr(runtime_cfg, "requires_multimodal_data", False)
|
||||
|
||||
return StageMetadata(
|
||||
stage_id=stage_id,
|
||||
stage_type=stage_type,
|
||||
engine_output_type=engine_output_type,
|
||||
is_comprehension=is_comprehension,
|
||||
requires_multimodal_data=requires_multimodal_data,
|
||||
engine_input_source=engine_input_source,
|
||||
final_output=final_output,
|
||||
final_output_type=final_output_type,
|
||||
default_sampling_params=default_sampling_params,
|
||||
custom_process_input_func=custom_process_input_func,
|
||||
model_stage=model_stage,
|
||||
runtime_cfg=runtime_cfg,
|
||||
prompt_expand_func=prompt_expand_func,
|
||||
)
|
||||
|
||||
|
||||
def prepare_engine_environment() -> None:
|
||||
"""One-time global setup: load plugins, set multiprocessing spawn method."""
|
||||
from vllm_omni.plugins import load_omni_general_plugins
|
||||
|
||||
load_omni_general_plugins()
|
||||
|
||||
if os.environ.get("VLLM_WORKER_MULTIPROC_METHOD") != "spawn":
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
logger.info("[stage_init] Set VLLM_WORKER_MULTIPROC_METHOD=spawn")
|
||||
try:
|
||||
mp.set_start_method("spawn", force=True)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
|
||||
def setup_stage_devices(stage_id: int, runtime_cfg: Any) -> None:
|
||||
"""Device mapping via set_stage_devices for a single stage."""
|
||||
try:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
device_type = current_omni_platform.device_type
|
||||
set_stage_devices(
|
||||
stage_id,
|
||||
runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else None,
|
||||
device_type=device_type,
|
||||
)
|
||||
logger.info(
|
||||
"[stage_init] Stage-%s set devices for %s, runtime devices: %s",
|
||||
stage_id,
|
||||
device_type,
|
||||
runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else None,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Device setup failed for stage %s: %s", stage_id, e)
|
||||
|
||||
|
||||
def build_engine_args_dict(
|
||||
stage_config: Any,
|
||||
model: str,
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the normalized engine args dict for one stage."""
|
||||
engine_args = stage_config.engine_args
|
||||
stage_type = getattr(stage_config, "stage_type", "llm")
|
||||
stage_id = stage_config.stage_id
|
||||
|
||||
engine_args_dict = _to_dict(engine_args)
|
||||
model = _resolve_model_tokenizer_paths(model, engine_args_dict)
|
||||
engine_args_dict["model"] = model
|
||||
# Stage id must come from stage config instead of inherited CLI kwargs
|
||||
# (e.g. `--stage-id` defaulting to None).
|
||||
engine_args_dict["stage_id"] = stage_id
|
||||
if engine_args_dict.get("async_chunk", False):
|
||||
engine_args_dict["stage_connector_spec"] = dict(stage_connector_spec or {})
|
||||
|
||||
if stage_type != "diffusion":
|
||||
resolve_worker_cls(engine_args_dict)
|
||||
|
||||
return engine_args_dict
|
||||
|
||||
|
||||
def build_vllm_config(
|
||||
stage_config: Any,
|
||||
model: str,
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
engine_args_dict: dict[str, Any] | None = None,
|
||||
) -> tuple[Any, type]:
|
||||
"""Build engine args, then create VllmConfig and executor_class.
|
||||
|
||||
Returns:
|
||||
(vllm_config, executor_class)
|
||||
"""
|
||||
if engine_args_dict is None:
|
||||
engine_args_dict = build_engine_args_dict(
|
||||
stage_config,
|
||||
model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
)
|
||||
|
||||
filtered_engine_args_dict = filter_dataclass_kwargs(OmniEngineArgs, engine_args_dict)
|
||||
omni_engine_args = OmniEngineArgs(**filtered_engine_args_dict)
|
||||
vllm_config = omni_engine_args.create_engine_config(usage_context=UsageContext.LLM_CLASS)
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
return vllm_config, executor_class
|
||||
|
||||
|
||||
def acquire_device_locks(
|
||||
stage_id: int,
|
||||
engine_args_dict: dict[str, Any],
|
||||
stage_init_timeout: int = 300,
|
||||
) -> list[int]:
|
||||
"""Acquire exclusive file locks on devices needed by this stage.
|
||||
|
||||
Returns list of lock file descriptors that must be released after init.
|
||||
"""
|
||||
lock_fds: list[int] = []
|
||||
try:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
# Get parallel sizes
|
||||
if "parallel_config" in engine_args_dict:
|
||||
pc = engine_args_dict["parallel_config"]
|
||||
tensor_parallel_size = pc.get("tensor_parallel_size", 1)
|
||||
pipeline_parallel_size = pc.get("pipeline_parallel_size", 1)
|
||||
data_parallel_size = pc.get("data_parallel_size", 1)
|
||||
prefill_context_parallel_size = pc.get("prefill_context_parallel_size", 1)
|
||||
sequence_parallel_size = pc.get("sequence_parallel_size", 1)
|
||||
cfg_parallel_size = pc.get("cfg_parallel_size", 1)
|
||||
else:
|
||||
tensor_parallel_size = engine_args_dict.get("tensor_parallel_size", 1)
|
||||
pipeline_parallel_size = engine_args_dict.get("pipeline_parallel_size", 1)
|
||||
data_parallel_size = engine_args_dict.get("data_parallel_size", 1)
|
||||
prefill_context_parallel_size = engine_args_dict.get("prefill_context_parallel_size", 1)
|
||||
sequence_parallel_size = 1
|
||||
cfg_parallel_size = 1
|
||||
|
||||
num_devices_per_stage = (
|
||||
tensor_parallel_size
|
||||
* pipeline_parallel_size
|
||||
* data_parallel_size
|
||||
* prefill_context_parallel_size
|
||||
* sequence_parallel_size
|
||||
* cfg_parallel_size
|
||||
)
|
||||
|
||||
# Get physical device IDs
|
||||
device_control_env = current_omni_platform.device_control_env_var
|
||||
visible_devices_str = os.environ.get(device_control_env)
|
||||
physical_devices: list[int] = []
|
||||
|
||||
if visible_devices_str:
|
||||
try:
|
||||
physical_devices = [int(x.strip()) for x in visible_devices_str.split(",") if x.strip()]
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
if not physical_devices:
|
||||
num_devices = current_omni_platform.get_device_count()
|
||||
physical_devices = list(range(num_devices))
|
||||
|
||||
num_devices_to_lock = min(num_devices_per_stage, len(physical_devices))
|
||||
devices_to_lock = sorted(physical_devices[:num_devices_to_lock])
|
||||
|
||||
logger.debug(
|
||||
"Parallel config: TP=%d, PP=%d, DP=%d, PCP=%d, SP=%d, CFG=%d; will lock %d devices: %s",
|
||||
tensor_parallel_size,
|
||||
pipeline_parallel_size,
|
||||
data_parallel_size,
|
||||
prefill_context_parallel_size,
|
||||
sequence_parallel_size,
|
||||
cfg_parallel_size,
|
||||
num_devices_to_lock,
|
||||
devices_to_lock,
|
||||
)
|
||||
|
||||
# Acquire locks
|
||||
wait_start = time.time()
|
||||
for device_id in devices_to_lock:
|
||||
lock_file = f"/tmp/vllm_omni_device_{device_id}_init.lock"
|
||||
lock_acquired = False
|
||||
|
||||
while not lock_acquired:
|
||||
try:
|
||||
lock_fd = os.open(lock_file, os.O_CREAT | os.O_RDWR, 0o644)
|
||||
try:
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
os.ftruncate(lock_fd, 0)
|
||||
os.write(lock_fd, f"{os.getpid()}\n".encode())
|
||||
os.fsync(lock_fd)
|
||||
lock_acquired = True
|
||||
lock_fds.append(lock_fd)
|
||||
logger.debug("Acquired exclusive lock for device %s", device_id)
|
||||
except BlockingIOError:
|
||||
os.close(lock_fd)
|
||||
if time.time() - wait_start > stage_init_timeout:
|
||||
logger.warning(
|
||||
"Timeout waiting for device %s initialization lock, proceeding anyway",
|
||||
device_id,
|
||||
)
|
||||
break
|
||||
time.sleep(0.01)
|
||||
except OSError as e:
|
||||
logger.debug(
|
||||
"Failed to acquire lock for device %s: %s, continuing anyway",
|
||||
device_id,
|
||||
e,
|
||||
)
|
||||
try:
|
||||
os.close(lock_fd)
|
||||
except (OSError, NameError):
|
||||
pass
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(
|
||||
"[Stage-%s] Failed to set up sequential initialization lock: %s",
|
||||
stage_id,
|
||||
e,
|
||||
)
|
||||
|
||||
return lock_fds
|
||||
|
||||
|
||||
def release_device_locks(lock_fds: list[int]) -> None:
|
||||
"""Release file locks acquired by acquire_device_locks."""
|
||||
for lock_fd in lock_fds:
|
||||
try:
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_UN)
|
||||
os.close(lock_fd)
|
||||
logger.debug("Released initialization lock (fd=%s)", lock_fd)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def load_omni_transfer_config_for_model(model: str, config_path: str | None) -> Any:
|
||||
"""Load omni transfer config from an explicit path or resolved model config."""
|
||||
from vllm_omni.distributed.omni_connectors import load_omni_transfer_config
|
||||
|
||||
try:
|
||||
resolved_config_path = config_path or resolve_model_config_path(model)
|
||||
return load_omni_transfer_config(resolved_config_path)
|
||||
except Exception as e:
|
||||
logger.warning("[stage_init] Failed to load transfer config: %s", e)
|
||||
return None
|
||||
|
||||
|
||||
def get_stage_connector_spec(
|
||||
omni_transfer_config: Any,
|
||||
stage_id: int,
|
||||
async_chunk: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""Return the first connector spec for the stage when async chunking is enabled."""
|
||||
from vllm_omni.distributed.omni_connectors import get_stage_connector_config
|
||||
|
||||
if not async_chunk:
|
||||
return {}
|
||||
|
||||
stage_connectors_cfg = get_stage_connector_config(omni_transfer_config, stage_id)
|
||||
for cfg in stage_connectors_cfg.values():
|
||||
return dict(cfg.get("spec", {}))
|
||||
return {}
|
||||
|
||||
|
||||
def initialize_diffusion_stage(model: str, stage_cfg: Any, metadata: StageMetadata) -> Any:
|
||||
"""Build a diffusion stage client."""
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.stage_diffusion_client import StageDiffusionClient
|
||||
|
||||
od_config = OmniDiffusionConfig.from_kwargs(
|
||||
model=model,
|
||||
**_to_dict(stage_cfg.engine_args),
|
||||
)
|
||||
if metadata.cfg_kv_collect_func is not None:
|
||||
od_config.cfg_kv_collect_func = metadata.cfg_kv_collect_func
|
||||
return StageDiffusionClient(model, od_config, metadata)
|
||||
|
||||
|
||||
def close_started_llm_stage(started: StartedLlmStage) -> None:
|
||||
"""Close managers owned by a launched stage that never attached."""
|
||||
resources = (
|
||||
("engine manager", started.engine_manager),
|
||||
("coordinator", started.coordinator),
|
||||
)
|
||||
for resource_name, resource in resources:
|
||||
if resource is None:
|
||||
continue
|
||||
try:
|
||||
resource.close()
|
||||
except Exception as cleanup_error:
|
||||
logger.warning(
|
||||
"[stage_init] Failed to close launched %s for stage %s: %s",
|
||||
resource_name,
|
||||
started.stage_id,
|
||||
cleanup_error,
|
||||
)
|
||||
|
||||
|
||||
def finalize_initialized_stages(
|
||||
stage_clients: list[Any | None],
|
||||
input_processor: InputProcessor | None,
|
||||
) -> tuple[list[Any], list[Any], list[dict[str, Any]]]:
|
||||
"""Validate successful init and build runtime metadata lists."""
|
||||
if any(stage_client is None for stage_client in stage_clients):
|
||||
raise RuntimeError("Stage initialization completed with missing stage clients")
|
||||
|
||||
initialized_stage_clients = [stage_client for stage_client in stage_clients if stage_client is not None]
|
||||
default_sampling_params_list = [stage_client.default_sampling_params for stage_client in initialized_stage_clients]
|
||||
stage_metadata = [
|
||||
{
|
||||
"final_output": stage_client.final_output,
|
||||
"final_output_type": stage_client.final_output_type,
|
||||
"stage_type": stage_client.stage_type,
|
||||
}
|
||||
for stage_client in initialized_stage_clients
|
||||
]
|
||||
|
||||
if not isinstance(input_processor, InputProcessor):
|
||||
has_llm_stage = any(metadata.get("stage_type") != "diffusion" for metadata in stage_metadata)
|
||||
if has_llm_stage:
|
||||
raise RuntimeError("Failed to initialize stage-0 InputProcessor for LLM pipeline")
|
||||
|
||||
return initialized_stage_clients, default_sampling_params_list, stage_metadata
|
||||
|
||||
|
||||
def cleanup_failed_stage_initialization(
|
||||
stage_clients: list[Any | None],
|
||||
started_llm_stages: list[StartedLlmStage],
|
||||
) -> None:
|
||||
"""Shutdown attached stages and close any launched-but-unattached engines."""
|
||||
for cleanup_stage_id, stage_client in reversed(list(enumerate(stage_clients))):
|
||||
if stage_client is None:
|
||||
continue
|
||||
try:
|
||||
stage_client.shutdown()
|
||||
except Exception as cleanup_error:
|
||||
logger.warning(
|
||||
"[stage_init] Failed to shutdown initialized stage %s after init failure: %s",
|
||||
cleanup_stage_id,
|
||||
cleanup_error,
|
||||
)
|
||||
|
||||
for started in reversed(started_llm_stages):
|
||||
if stage_clients[started.stage_id] is not None:
|
||||
continue
|
||||
close_started_llm_stage(started)
|
||||
Reference in new issue
Block a user