[Docs] optimize and supplement docs system (#86)

Signed-off-by: Gaohan123 <gaohan19@huawei.com>
This commit is contained in:
Gao Han authored and GitHub committed 2025-11-28 11:03:52 +08:00
1 parent 38f58064eb
commit db81ee9f69
75 files changed
+2452 -512

No files matched your search

+22 -1
View File
@@ -10,7 +10,28 @@ import vllm_omni.model_executor.models as me_models
@config
@dataclass(config=ConfigDict(arbitrary_types_allowed=True))
class OmniModelConfig(ModelConfig):
"""Configuration for Omni models, extending the base ModelConfig."""
"""Configuration for Omni models, extending the base ModelConfig.
This configuration class extends the base vLLM ModelConfig with
omni-specific fields for multi-stage pipeline processing.
Attributes:
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.
Example:
>>> config = OmniModelConfig(
... stage_id=0,
... model_stage="thinker",
... model_arch="Qwen2_5OmniForConditionalGeneration"
... )
"""
stage_id: int = 0
model_stage: str = "thinker"
+15 -5
View File
@@ -14,12 +14,22 @@ from vllm_omni.outputs import OmniModelRunnerOutput
class DiffusionScheduler(OmniScheduler):
"""Scheduler for diffusion-based non-autoregressive stages.
Implements a fast-path scheduling strategy for diffusion models where
all input tokens are fed at once. Falls back to standard vLLM scheduling
if the token budget cannot accommodate all tokens in a single iteration.
"""
def schedule(self) -> SchedulerOutput:
"""Diffusion fast path:
- Feed all input tokens of the request at once
(if 0, allocate 1 placeholder token).
- If the token budget cannot be satisfied at once, fall back to the
default vLLM scheduling.
"""Schedule requests for diffusion model execution.
Uses a fast-path approach that feeds all input tokens at once
(or 1 placeholder token if input is empty). Falls back to
standard scheduling if token budget is insufficient.
Returns:
SchedulerOutput containing scheduled requests and token allocations
"""
# Select requests with zero prompt and using pooling
+20
View File
@@ -9,6 +9,17 @@ from vllm_omni.engine import AdditionalInformationPayload, PromptEmbedsPayload
@dataclass
class OmniNewRequestData(NewRequestData):
"""New request data for omni models with embeddings support.
Extends NewRequestData to include prompt embeddings and additional
information for direct transfer between pipeline stages.
Args:
prompt_embeds: Optional serialized prompt embeddings payload
additional_information: Optional serialized additional information
dictionary containing tensors or lists
"""
# Optional serialized prompt embeddings
prompt_embeds: Optional[PromptEmbedsPayload] = None
# Optional serialized additional information
@@ -20,6 +31,15 @@ class OmniNewRequestData(NewRequestData):
request: Request,
block_ids: tuple[list[int], ...],
) -> "OmniNewRequestData":
"""Create OmniNewRequestData from a Request object.
Args:
request: Request object to convert
block_ids: Tuple of block ID lists for KV cache allocation
Returns:
OmniNewRequestData instance with data from the request
"""
return cls(
req_id=request.request_id,
prompt_token_ids=request.prompt_token_ids,
+13
View File
@@ -49,6 +49,19 @@ class AdditionalInformationPayload(msgspec.Struct):
class OmniEngineCoreRequest(EngineCoreRequest):
"""Engine core request for omni models with embeddings support.
Extends the base EngineCoreRequest with support for prompt embeddings
and additional information payloads, enabling direct transfer of
pre-computed embeddings between pipeline stages.
Attributes:
prompt_embeds: Optional serialized prompt embeddings payload for
direct transfer between stages
additional_information: Optional serialized additional information
dictionary containing tensors or lists to pass along with the request
"""
# Optional prompt embeddings (direct-transfer version)
prompt_embeds: Optional[PromptEmbedsPayload] = None
# Optional additional information dictionary (serialized)
+42
View File
@@ -9,12 +9,33 @@ from vllm_omni.config import OmniModelConfig
@dataclass
class OmniEngineArgs(EngineArgs):
"""Engine arguments for omni models, extending base EngineArgs.
Adds omni-specific configuration fields for multi-stage pipeline
processing and output type specification.
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_id: int = 0
model_stage: str = "thinker"
model_arch: str = "Qwen2_5OmniForConditionalGeneration"
engine_output_type: Optional[str] = None
def create_model_config(self) -> OmniModelConfig:
"""Create an OmniModelConfig from these engine arguments.
Returns:
OmniModelConfig instance with all configuration fields set
"""
# First, get the base ModelConfig from the parent class
base_config = super().create_model_config()
@@ -37,12 +58,33 @@ class OmniEngineArgs(EngineArgs):
@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_id: int = 0
model_stage: str = "thinker"
model_arch: str = "Qwen2_5OmniForConditionalGeneration"
engine_output_type: Optional[str] = None
def create_model_config(self) -> OmniModelConfig:
"""Create an OmniModelConfig from these engine arguments.
Returns:
OmniModelConfig instance with all configuration fields set
"""
# First, get the base ModelConfig from the parent class
base_config = super().create_model_config()
+84
View File
@@ -19,6 +19,13 @@ logger = init_logger(__name__)
class OmniRequestState(RequestState):
"""Request state for omni models, tracking multimodal outputs.
Extends the base RequestState with support for accumulating
multimodal tensor outputs (e.g., images, audio, latents) that
are produced incrementally during generation.
"""
def __init__(
self,
*args,
@@ -86,6 +93,17 @@ class OmniRequestState(RequestState):
)
def add_multimodal_tensor(self, tensor: Optional[torch.Tensor], mm_type: Optional[str]) -> None:
"""Add a multimodal tensor to the accumulated outputs.
Accumulates multimodal tensors (e.g., image latents, audio waveforms)
that are produced incrementally during generation. Tensors are
concatenated along the first dimension.
Args:
tensor: Optional tensor to add. If None, this is a no-op.
mm_type: Optional modality type identifier (e.g., "image", "audio").
Used to categorize the output type.
"""
if tensor is None:
return
try:
@@ -115,6 +133,23 @@ class OmniRequestState(RequestState):
stop_reason: Optional[Union[int, str]],
kv_transfer_params: Optional[dict[str, Any]] = None,
) -> Optional[Union[OmniRequestOutput, PoolingRequestOutput]]:
"""Create a request output from generation results.
Creates a RequestOutput or PoolingRequestOutput from the generated
tokens and accumulated multimodal outputs. Attaches multimodal
tensors to the completion output if available.
Args:
new_token_ids: List of newly generated token IDs
pooling_output: Optional pooling output tensor
finish_reason: Optional finish reason indicating why generation stopped
stop_reason: Optional stop reason (token ID or stop string)
kv_transfer_params: Optional KV cache transfer parameters
Returns:
OmniRequestOutput or PoolingRequestOutput if output should be
emitted (based on finish status and output kind), None otherwise
"""
finished = finish_reason is not None
final_only = self.output_kind == RequestOutputKind.FINAL_ONLY
@@ -179,6 +214,15 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
log_stats: bool,
engine_core_output_type: Optional[str] = None,
):
"""Initialize the multimodal output processor.
Args:
tokenizer: Tokenizer for detokenizing text outputs
log_stats: Whether to log statistics
engine_core_output_type: Optional output type specification
(e.g., "image", "audio", "latents"). Used to route outputs
to appropriate processors. If None, output type is inferred.
"""
super().__init__(tokenizer=tokenizer, log_stats=log_stats)
self.output_handlers: dict[str, Callable[[EngineCoreOutput], None]] = {}
self._reqid_to_mm_type: dict[str, str] = {}
@@ -186,6 +230,16 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
self.engine_core_output_type = engine_core_output_type
def register_handler(self, modality: str, handler: Callable[[EngineCoreOutput], None]) -> None:
"""Register a custom handler for a specific modality.
Allows custom processing logic for specific output modalities.
The handler is called before default processing for outputs
matching the specified modality.
Args:
modality: Modality name (e.g., "image", "audio", "latents")
handler: Callable that takes an EngineCoreOutput and processes it
"""
self.output_handlers[modality.lower()] = handler
def add_request(
@@ -196,6 +250,21 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
request_index: int = 0,
queue: Optional[RequestOutputCollector] = None,
) -> None:
"""Add a new request to be processed.
Creates an OmniRequestState for the request and registers it
for output processing.
Args:
request: Engine core request to add
prompt: Optional prompt string for the request
parent_req: Optional parent request for parallel sampling
request_index: Index of the request in the batch
queue: Optional queue for collecting outputs
Raises:
ValueError: If the request ID is already registered
"""
request_id = request.request_id
if request_id in self.request_states:
raise ValueError(f"Request id {request_id} already running.")
@@ -220,6 +289,21 @@ class MultimodalOutputProcessor(VLLMOutputProcessor):
engine_core_timestamp: Optional[float] = None,
iteration_stats: Optional[IterationStats] = None,
) -> OutputProcessorOutput:
"""Process engine core outputs into request outputs.
Converts EngineCoreOutput objects into RequestOutput objects,
handling multimodal outputs by routing them through appropriate
processors and accumulating tensors in request states.
Args:
engine_core_outputs: List of engine core outputs to process
engine_core_timestamp: Optional timestamp for the outputs
iteration_stats: Optional iteration statistics
Returns:
OutputProcessorOutput containing processed request outputs
and list of request IDs to abort
"""
self._reqid_to_mm_type.clear()
for eco in engine_core_outputs:
mm_type = (self.engine_core_output_type or "").lower()
+49
View File
@@ -30,8 +30,28 @@ logger = init_logger(__name__)
class OmniProcessor(Processor):
"""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
tokenizer: Tokenizer instance for text processing
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",
@@ -78,6 +98,35 @@ class OmniProcessor(Processor):
priority: int = 0,
data_parallel_rank: Optional[int] = None,
) -> tuple[Optional[str], 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
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
Returns:
Tuple of (prompt_string, OmniEngineCoreRequest) where:
- prompt_string: The original prompt as a string, or None if
using embeddings
- OmniEngineCoreRequest: Processed request ready for the engine
Raises:
ValueError: If data_parallel_rank is out of range or prompt_embeds
has incorrect shape
"""
# TODO(woosuk): Support pooling models.
# TODO(woosuk): Support encoder-decoder models.
self._validate_lora(lora_request)
+96 -5
View File
@@ -53,6 +53,38 @@ logger = init_logger(__name__)
class AsyncOmniLLM(EngineClient):
"""Async entry point for vLLM-omni inference.
This class provides an asynchronous interface for running multi-modal
comprehension and generation models. It orchestrates multiple
stages in a pipeline, where each stage runs in a separate process.
Designed for use with async/await patterns and streaming generation.
Args:
model: Model name or path to load
stage_configs_path: Optional path to YAML file containing stage
configurations. If None, configurations are loaded from the model.
log_stats: Whether to enable statistics logging
log_file: Optional path prefix for log files. If provided, logs will
be written to files with stage-specific suffixes.
init_sleep_seconds: Number of seconds to sleep between starting
each stage process during initialization
shm_threshold_bytes: Threshold in bytes for using shared memory
for IPC. Objects larger than this threshold will use shared memory.
batch_timeout: Timeout in seconds for batching requests within a stage
init_timeout: Timeout in seconds for waiting for all stages to initialize
**kwargs: Additional keyword arguments passed to stage engines
Example:
>>> async_llm = AsyncOmniLLM(model="Qwen/Qwen2.5-Omni-7B")
>>> async for output in async_llm.generate(
... prompt="Hello",
... request_id="req-1",
... sampling_params_list=[SamplingParams(), SamplingParams()]
... ):
... print(output)
"""
def __init__(
self,
model: str,
@@ -63,7 +95,7 @@ class AsyncOmniLLM(EngineClient):
shm_threshold_bytes: int = 65536,
batch_timeout: int = 10,
init_timeout: int = 300,
**kwargs,
**kwargs: Any,
):
self.batch_timeout = batch_timeout
self._enable_stats: bool = bool(log_stats)
@@ -140,6 +172,12 @@ class AsyncOmniLLM(EngineClient):
time.sleep(self._init_sleep_seconds)
def close(self) -> None:
"""Close all stage processes and clean up resources.
Sends shutdown signals to all stage input queues and stops
all stage worker processes. This method should be called
when done using the AsyncOmniLLM instance.
"""
for q in self._stage_in_queues:
try:
q.put_nowait(None)
@@ -162,7 +200,11 @@ class AsyncOmniLLM(EngineClient):
logger.debug("[Orchestrator] __del__ close() raised: %s", e, exc_info=True)
def shutdown(self):
"""Shutdown, cleaning up the background proc and IPC."""
"""Shutdown, cleaning up the background proc and IPC.
Alias for close() method. Cleans up all stage processes
and inter-process communication resources.
"""
try:
self.close()
except Exception as e:
@@ -178,6 +220,33 @@ class AsyncOmniLLM(EngineClient):
priority: int = 0,
data_parallel_rank: Optional[int] = None,
) -> AsyncGenerator[OmniRequestOutput, None]:
"""Generate outputs for the given prompt asynchronously.
Processes the prompt through all stages in the pipeline and yields
outputs as they become available. Each stage uses its corresponding
sampling parameters from the sampling_params_list.
Args:
prompt: Prompt to process. Can be a text string, token IDs,
or multimodal prompt.
request_id: Unique identifier for this request
sampling_params_list: List of SamplingParams, one for each stage.
Must have the same length as the number of stages.
If None, uses default sampling params for each stage.
lora_request: Optional LoRA adapter request for this generation
trace_headers: Optional tracing headers for observability
priority: Request priority (higher values processed first)
data_parallel_rank: Optional data parallel rank for distributed
inference
Yields:
OmniRequestOutput objects as they are produced by each stage.
Each output contains the stage_id, final_output_type, and
the request_output from that stage.
Raises:
ValueError: If sampling_params_list has incorrect length.
"""
logger.debug("[Orchestrator] generate() called")
if sampling_params_list is None:
sampling_params_list = self.default_sampling_params_list
@@ -510,9 +579,6 @@ class AsyncOmniLLM(EngineClient):
return None
async def get_input_preprocessor(self) -> InputPreprocessor:
# for stage in self.stage_list:
# if stage.is_comprehension:
# return stage.input_preprocessor
return None
async def get_tokenizer(self) -> AnyTokenizer:
@@ -569,6 +635,31 @@ class AsyncOmniLLM(EngineClient):
class AsyncOmniStageLLM(AsyncLLM):
"""Async single-stage LLM engine for use within a stage worker process.
This class extends the base vLLM AsyncLLM class with omni-specific
processors for handling multimodal inputs and outputs. It is used
internally by AsyncOmniStage workers and should not be instantiated
directly by users.
Args:
engine_args: AsyncOmniEngineArgs containing engine configuration
vllm_config: Global vLLM configuration
executor_class: Executor implementation class, e.g. MultiprocExecutor
log_stats: Whether to log statistics
usage_context: Usage context of the LLM (default: ENGINE_CONTEXT)
mm_registry: Multi-modal registry for processing multimodal inputs
use_cached_outputs: Whether to use cached outputs
log_requests: Whether to log requests
start_engine_loop: Whether to start the engine loop automatically
stat_loggers: Customized stat loggers for the engine.
If not provided, default stat loggers will be used.
Note: Stat logger interface may change in V1.
client_addresses: Optional dictionary mapping client names to addresses
client_count: Total number of clients (default: 1)
client_index: Index of this client (default: 0)
"""
def __init__(
self,
engine_args: AsyncOmniEngineArgs,
+76 -6
View File
@@ -42,11 +42,36 @@ logger = init_logger(__name__)
class OmniLLM:
"""Multi-process pipelined OmniLLM.
"""Main entry point for vLLM-omni inference.
- Per-stage process with copy-based IPC (Queues)
- window=-1 across stages (downstream starts when upstream finishes)
- max_inflight=1 per stage (serial within a stage), but pipeline across stages
This class provides a high-level interface for running multi-modal
comprehension and generation models. It orchestrates multiple
stages in a pipeline, where each stage runs in a separate process
with copy-based IPC (Queues). Downstream stages start when upstream
stages finish (window=-1), and each stage processes requests serially
(max_inflight=1) but pipelines across stages.
Args:
model: Model name or path to load
stage_configs_path: Optional path to YAML file containing stage
configurations. If None, configurations are loaded from the model.
log_stats: Whether to enable statistics logging
log_file: Optional path prefix for log files. If provided, logs will
be written to files with stage-specific suffixes.
init_sleep_seconds: Number of seconds to sleep between starting
each stage process during initialization
shm_threshold_bytes: Threshold in bytes for using shared memory
for IPC. Objects larger than this threshold will use shared memory.
batch_timeout: Timeout in seconds for batching requests within a stage
init_timeout: Timeout in seconds for waiting for all stages to initialize
**kwargs: Additional keyword arguments passed to stage engines
Example:
>>> llm = OmniLLM(model="Qwen/Qwen2.5-Omni-7B")
>>> outputs = llm.generate(
... prompts="Hello",
... sampling_params_list=[SamplingParams(), SamplingParams()]
... )
"""
def __init__(
@@ -59,7 +84,7 @@ class OmniLLM:
shm_threshold_bytes: int = 65536,
batch_timeout: int = 10,
init_timeout: int = 300,
**kwargs,
**kwargs: Any,
):
self.batch_timeout = batch_timeout
self._enable_stats: bool = bool(log_stats)
@@ -132,6 +157,12 @@ class OmniLLM:
time.sleep(self._init_sleep_seconds)
def close(self) -> None:
"""Close all stage processes and clean up resources.
Sends shutdown signals to all stage input queues and stops
all stage worker processes. This method should be called
when done using the OmniLLM instance.
"""
for q in self._stage_in_queues:
try:
q.put_nowait(None)
@@ -157,6 +188,27 @@ class OmniLLM:
prompts: Union[PromptType, Sequence[PromptType]],
sampling_params_list: Optional[Union[SamplingParams, Sequence[SamplingParams]]] = None,
) -> list[OmniRequestOutput]:
"""Generate outputs for the given prompts.
Processes prompts through all stages in the pipeline and returns
the final outputs. Each stage uses its corresponding sampling
parameters from the sampling_params_list.
Args:
prompts: Single prompt or sequence of prompts to process.
Can be text strings, token IDs, or multimodal prompts.
sampling_params_list: List of SamplingParams, one for each stage.
Must have the same length as the number of stages.
Required for pipelined generation.
Returns:
List of OmniRequestOutput objects, one for each input prompt.
Each output contains the stage_id, final_output_type, and
the request_output from the final stage.
Raises:
ValueError: If sampling_params_list is None or has incorrect length.
"""
try:
return self._run_generation(prompts, sampling_params_list)
except Exception as e:
@@ -465,13 +517,31 @@ class OmniLLM:
class OmniStageLLM(LLM):
"""Single-stage LLM engine for use within a stage worker process.
This class extends the base vLLM LLM class with omni-specific
processors for handling multimodal inputs and outputs. It is used
internally by OmniStage workers and should not be instantiated directly
by users.
Args:
model: Model name or path to load
compilation_config: Optional compilation configuration. Can be an
integer (compilation level), dict, or CompilationConfig instance.
hf_overrides: Optional HuggingFace model configuration overrides
structured_outputs_config: Optional structured outputs configuration.
Can be a dict or StructuredOutputsConfig instance.
**kwargs: Additional keyword arguments passed to the base LLM class
and engine
"""
def __init__(
self,
model: str,
compilation_config: Optional[Union[int, dict[str, Any], CompilationConfig]] = None,
hf_overrides: Optional[HfOverrides] = None,
structured_outputs_config: Optional[Union[dict[str, Any], StructuredOutputsConfig]] = None,
**kwargs,
**kwargs: Any,
):
"""LLM constructor."""
if "disable_log_stats" not in kwargs:
+104 -11
View File
@@ -39,7 +39,18 @@ logger = init_logger(__name__)
class OmniStage:
def __init__(self, stage_config):
"""Stage manager for orchestrating a single stage in the omni pipeline.
Encapsulates per-stage process lifecycle and worker logic, including
device setup, LLM initialization, batching, and shared-memory IPC.
Preserves input processing utilities for cross-stage data wiring.
Args:
stage_config: Stage configuration object containing engine arguments,
runtime settings, and stage-specific parameters
"""
def __init__(self, stage_config: Any):
self.stage_config = stage_config
self.engine = None
self.async_engine = None
@@ -76,35 +87,69 @@ class OmniStage:
self._logger = logging.getLogger(__name__)
def set_engine(self, engine: LLMEngine) -> None:
"""Initialize the engine for the stage."""
"""Set the LLM engine for this stage.
Args:
engine: LLMEngine instance to use for this stage
"""
self.engine = engine
def set_async_engine(self, async_engine: AsyncLLM) -> None:
"""Initialize the async engine for the stage."""
"""Set the async LLM engine for this stage.
Args:
async_engine: AsyncLLM instance to use for this stage
"""
self.async_engine = async_engine
def set_vllm_config(self, vllm_config) -> None:
"""Set the vllm_config for the stage (received from worker process)."""
def set_vllm_config(self, vllm_config: Any) -> None:
"""Set the vLLM configuration for this stage.
Args:
vllm_config: VllmConfig instance received from worker process
"""
self.vllm_config = vllm_config
def set_tokenizer(self, tokenizer: AnyTokenizer) -> None:
"""Set the tokenizer for the stage (received from worker process)."""
"""Set the tokenizer for this stage.
Args:
tokenizer: Tokenizer instance received from worker process
"""
self.tokenizer = tokenizer
def set_input_preprocessor(self, input_preprocessor: InputPreprocessor) -> None:
"""Set the input preprocessor for the stage (received from worker process)."""
"""Set the input preprocessor for this stage.
Args:
input_preprocessor: InputPreprocessor instance received from worker process
"""
self.input_preprocessor = input_preprocessor
def set_is_tracing_enabled(self, is_tracing_enabled: bool) -> None:
"""Set the is_tracing_enabled for the stage (received from worker process)."""
"""Set whether tracing is enabled for this stage.
Args:
is_tracing_enabled: Boolean indicating if tracing is enabled
"""
self.is_tracing_enabled = is_tracing_enabled
def set_engine_outputs(self, engine_outputs: EngineCoreOutput) -> None:
"""Set the engine output for the stage."""
"""Set the engine outputs for this stage.
Args:
engine_outputs: EngineCoreOutput from this stage's processing
"""
self.engine_outputs = engine_outputs
# ----------------- New Orchestration APIs -----------------
def attach_queues(self, in_q: mp.Queue, out_q: mp.Queue) -> None:
"""Attach input and output queues for IPC communication.
Args:
in_q: Input queue for receiving tasks from orchestrator
out_q: Output queue for sending results to orchestrator
"""
self._in_q = in_q
self._out_q = out_q
@@ -118,6 +163,22 @@ class OmniStage:
ctx: Optional[mp.context.BaseContext] = None,
batch_timeout: int = 10,
) -> None:
"""Initialize and start the stage worker process.
Creates a worker process that runs the LLM engine for this stage.
The worker handles batching, generation, and IPC communication.
Args:
model: Model name or path to load
is_async: Whether to use async engine (default: False)
log_file: Optional log file path prefix for stage-specific logs
shm_threshold_bytes: Threshold for using shared memory for IPC
ctx: Optional multiprocessing context (default: spawn)
batch_timeout: Timeout in seconds for batching requests
Raises:
AssertionError: If queues are not attached before calling this method
"""
assert self._in_q is not None and self._out_q is not None, "Queues must be attached before start_process"
self._log_file = log_file
self._shm_threshold_bytes = shm_threshold_bytes
@@ -156,6 +217,11 @@ class OmniStage:
self._proc.start()
def stop_stage_worker(self) -> None:
"""Stop the stage worker process gracefully.
Sends shutdown signal to the worker and waits for it to terminate.
If graceful shutdown fails, forcefully terminates the process.
"""
if self._in_q is not None:
try:
self._in_q.put_nowait(None)
@@ -173,10 +239,22 @@ class OmniStage:
self._logger.warning("[Stage-%s] terminate() failed: %s", self.stage_id, e)
def submit(self, payload: dict[str, Any]) -> None:
"""Submit a task to the stage worker.
Args:
payload: Dictionary containing task data (request_id, engine_inputs,
sampling_params, etc.)
"""
assert self._in_q is not None
self._in_q.put(payload)
def try_collect(self) -> Optional[dict[str, Any]]:
"""Try to collect a result from the stage worker without blocking.
Returns:
Result dictionary if available, None otherwise. Result contains
request_id, engine_outputs (or engine_outputs_shm), and metrics.
"""
assert self._out_q is not None
try:
return self._out_q.get_nowait()
@@ -184,9 +262,24 @@ class OmniStage:
return None
def process_engine_inputs(
self, stage_list, prompt: Union[OmniTokensPrompt, TextPrompt] = None
self, stage_list: list[Any], prompt: Union[OmniTokensPrompt, TextPrompt] = None
) -> list[Union[OmniTokensPrompt, TextPrompt]]:
"""Process the engine input for the stage."""
"""Process engine inputs for this stage from upstream stage outputs.
Derives inputs for this stage from outputs of upstream stages.
Uses engine_input_source configuration to determine which upstream
stage outputs to use. Supports custom processing functions.
Args:
stage_list: List of all stages in the pipeline
prompt: Optional original prompt (for multimodal data preservation)
Returns:
List of processed engine inputs ready for this stage
Raises:
ValueError: If engine_input_source is empty or invalid
"""
if self.custom_process_input_func is None:
engine_inputs = []
if len(self.engine_input_source) == 0:
+42 -5
View File
@@ -114,6 +114,21 @@ async def build_async_omni_llm(
disable_frontend_multiprocessing: Optional[bool] = None,
client_config: Optional[dict[str, Any]] = None,
) -> AsyncIterator[EngineClient]:
"""Build an AsyncOmniLLM instance from command-line arguments.
Creates an async context manager that yields an AsyncOmniLLM instance
configured from the provided arguments. Handles forkserver setup if
needed and ensures proper cleanup on exit.
Args:
args: Parsed command-line arguments containing model and configuration
disable_frontend_multiprocessing: Optional flag to disable frontend
multiprocessing (deprecated in V1)
client_config: Optional client configuration dictionary
Yields:
EngineClient instance (AsyncOmniLLM) ready for use
"""
if os.getenv("VLLM_WORKER_MULTIPROC_METHOD") == "forkserver":
# The executor is expected to be mp.
# Pre-import heavy modules in the forkserver process
@@ -139,12 +154,23 @@ async def build_async_omni_llm_from_stage_config(
disable_frontend_multiprocessing: bool = False,
client_config: Optional[dict[str, Any]] = None,
) -> AsyncIterator[EngineClient]:
"""
Create AsyncOmniLLM, either:
- in-process using the AsyncOmniLLM Directly
- multiprocess using AsyncOmniLLM RPC
"""Create AsyncOmniLLM from stage configuration.
Returns the AsyncOmniLLM or None if the creation failed.
Creates an AsyncOmniLLM instance either in-process or using multiprocess
RPC. Loads stage configurations from the model or from a specified path.
Args:
args: Parsed command-line arguments containing model and stage configs
disable_frontend_multiprocessing: Flag to disable frontend multiprocessing
(deprecated in V1)
client_config: Optional client configuration dictionary
Yields:
EngineClient instance (AsyncOmniLLM) ready for use
Note:
Stage configurations are loaded from args.stage_configs_path if provided,
otherwise from the model's default configuration.
"""
# V1 AsyncLLM.
@@ -179,6 +205,17 @@ async def omni_init_app_state(
state: State,
args: Namespace,
) -> None:
"""Initialize the FastAPI application state for omni API server.
Sets up the application state with model information, request logger,
and other server configuration needed for handling API requests.
Args:
engine_client: Engine client instance (AsyncOmniLLM)
vllm_config: vLLM configuration object
state: FastAPI application state object to initialize
args: Parsed command-line arguments
"""
if args.served_model_name is not None:
served_model_names = args.served_model_name
else:
+25 -4
View File
@@ -13,8 +13,22 @@ logger = logging.getLogger(__name__)
PROJECT_ROOT = Path(__file__).parent.parent.parent
def load_stage_configs_from_model(model: str):
"""Load stage configs from model."""
def load_stage_configs_from_model(model: str) -> list:
"""Load stage configurations from model's default config file.
Loads stage configurations based on the model type. Looks for a
YAML configuration file in the stage_configs directory matching
the model's model_type.
Args:
model: Model name or path (used to determine model_type)
Returns:
List of stage configuration dictionaries
Raises:
FileNotFoundError: If no stage config file exists for the model type
"""
hf_config = get_config(model, trust_remote_code=True)
model_type = hf_config.model_type
stage_config_file = f"vllm_omni/model_executor/stage_configs/{model_type}.yaml"
@@ -25,7 +39,14 @@ def load_stage_configs_from_model(model: str):
return stage_configs
def load_stage_configs_from_yaml(config_path: str):
"""Load stage configs from yaml file."""
def load_stage_configs_from_yaml(config_path: str) -> list:
"""Load stage configurations from a YAML file.
Args:
config_path: Path to the YAML configuration file
Returns:
List of stage configuration dictionaries from the file's stage_args
"""
config_data = OmegaConf.load(config_path)
return config_data.stage_args
+50 -1
View File
@@ -11,6 +11,17 @@ from vllm.inputs.data import EmbedsPrompt, TokenInputs, TokensPrompt
class OmniTokensPrompt(TokensPrompt):
"""Tokens prompt with optional embeddings and additional information.
Extends TokensPrompt to support prompt embeddings and additional
information payloads for direct transfer between pipeline stages.
Attributes:
prompt_embeds: Optional tensor containing prompt embeddings
additional_information: Optional dictionary containing additional
information (tensors or lists) to pass along with the prompt
"""
prompt_embeds: NotRequired[torch.Tensor]
"""The embeddings of the prompt."""
@@ -20,6 +31,18 @@ class OmniTokensPrompt(TokensPrompt):
class OmniTokenInputs(TokenInputs):
"""Token inputs with optional embeddings and additional information.
Extends TokenInputs to support prompt embeddings and additional
information payloads for direct transfer between pipeline stages.
Attributes:
prompt_embeds: Optional tensor containing prompt embeddings
aligned with token IDs
additional_information: Optional dictionary containing additional
information (tensors or lists) to pass along with the inputs
"""
# New: optional prompt embeddings aligned with token ids
prompt_embeds: NotRequired[torch.Tensor]
@@ -29,6 +52,17 @@ class OmniTokenInputs(TokenInputs):
class OmniEmbedsPrompt(EmbedsPrompt):
"""Embeddings prompt with optional additional information.
Extends EmbedsPrompt to support additional information payloads
for direct transfer between pipeline stages.
Attributes:
prompt_embeds: Optional tensor containing prompt embeddings
additional_information: Optional dictionary containing additional
information (tensors or lists) to pass along with the prompt
"""
# New: optional prompt embeddings aligned with token ids
prompt_embeds: NotRequired[torch.Tensor]
@@ -44,7 +78,22 @@ def token_inputs_omni(
prompt_embeds: Optional[torch.Tensor] = None,
additional_information: Optional[dict[str, Any]] = None,
) -> OmniTokenInputs:
"""Construct token inputs with optional embeddings and metadata."""
"""Construct token inputs with optional embeddings and metadata.
Creates an OmniTokenInputs object with token IDs and optional
embeddings and additional information for pipeline stage transfer.
Args:
prompt_token_ids: List of token IDs for the prompt
prompt: Optional prompt string
cache_salt: Optional cache salt for prefix caching
prompt_embeds: Optional tensor containing prompt embeddings
additional_information: Optional dictionary containing additional
information (tensors or lists)
Returns:
OmniTokenInputs instance with the provided data
"""
inputs = OmniTokenInputs(type="token", prompt_token_ids=prompt_token_ids)
if prompt is not None:
+17
View File
@@ -9,6 +9,23 @@ from vllm.inputs.parse import (
def parse_singleton_prompt_omni(prompt: SingletonPrompt) -> ParsedSingletonPrompt:
"""Parse a singleton prompt into a typed parsed prompt.
Handles omni-specific prompt types including tokens prompts with
embeddings and additional information. Supports string, text,
tokens, and embeddings prompts.
Args:
prompt: Singleton prompt to parse. Can be a string, TextPrompt,
TokensPrompt (with optional prompt_embeds and additional_information),
or EmbedsPrompt.
Returns:
ParsedSingletonPrompt containing the parsed prompt with type information
Raises:
TypeError: If the prompt type is not supported
"""
if isinstance(prompt, str):
return ParsedStrPrompt(type="str", content=prompt)
elif isinstance(prompt, dict):
+7
View File
@@ -13,6 +13,13 @@ logger = init_logger(__name__)
class OmniInputPreprocessor(InputPreprocessor):
"""Input preprocessor for omni models.
Extends the base InputPreprocessor to handle omni-specific input
types including prompt embeddings and additional information payloads.
Supports processing tokens, embeddings, text, and multimodal inputs.
"""
def _process_tokens(
self,
parsed_content: TokensPrompt,
@@ -11,9 +11,9 @@ stage_args:
worker_cls: vllm_omni.worker.gpu_ar_worker.GPUARWorker
scheduler_cls: vllm_omni.core.sched.scheduler.OmniScheduler
gpu_memory_utilization: 0.8
enforce_eager: true # need to discuss
enforce_eager: true # Now we only support eager mode
trust_remote_code: true
engine_output_type: latent # change the param name,such as pooling_output
engine_output_type: latent
enable_prefix_caching: false
is_comprehension: true
final_output: true
+23
View File
@@ -7,11 +7,34 @@ from vllm.v1.outputs import ModelRunnerOutput
class OmniModelRunnerOutput(ModelRunnerOutput):
"""Model runner output for omni models.
Extends the base ModelRunnerOutput with support for multimodal outputs
that may be produced by non-autoregressive stages.
Attributes:
multimodal_outputs: Optional dictionary mapping modality names to
output tensors (e.g., {"image": tensor, "audio": tensor})
"""
multimodal_outputs: Optional[dict[str, torch.Tensor]] = None
@dataclass
class OmniRequestOutput(RequestOutput):
"""Request output for omni pipeline stages.
Wraps a standard RequestOutput with stage-specific metadata,
indicating which stage produced the output and what type of
final output it represents.
Attributes:
stage_id: Identifier of the stage that produced this output
final_output_type: Type of final output (e.g., "text", "image",
"audio", "latents")
request_output: The underlying RequestOutput from the stage
"""
stage_id: int
final_output_type: str
request_output: RequestOutput
+23
View File
@@ -10,6 +10,19 @@ from vllm_omni.engine import AdditionalInformationPayload, OmniEngineCoreRequest
class OmniRequest(Request):
"""Request class for omni models, extending the base Request.
This class extends the base vLLM Request with support for prompt
embeddings and additional information payloads, enabling direct
transfer of pre-computed embeddings between stages.
Args:
prompt_embeds: Optional serialized prompt embeddings payload.
Used for direct transfer of embeddings between stages.
additional_information: Optional additional information payload
containing tensors or lists to be passed along with the request.
"""
def __init__(
self,
prompt_embeds: Optional[PromptEmbedsPayload] = None,
@@ -29,6 +42,16 @@ class OmniRequest(Request):
request: OmniEngineCoreRequest,
block_hasher: Optional[Callable[["Request"], list["BlockHash"]]],
) -> "Request":
"""Create an OmniRequest from an OmniEngineCoreRequest.
Args:
request: The OmniEngineCoreRequest to convert
block_hasher: Optional function to compute block hashes for
prefix caching
Returns:
OmniRequest instance created from the engine core request
"""
return cls(
request_id=request.request_id,
client_index=request.client_index,
+16
View File
@@ -13,7 +13,23 @@ from vllm_omni.worker.gpu_ar_model_runner import GPUARModelRunner
class GPUARWorker(GPUWorker):
"""GPU worker for autoregressive omni model stages.
Extends the base GPUWorker to initialize and manage autoregressive
model runners for text generation stages (e.g., thinker stages).
"""
def init_device(self):
"""Initialize the GPU device and autoregressive model runner.
Sets up CUDA device, initializes distributed environment,
sets random seed, and creates a GPUARModelRunner instance.
Raises:
ValueError: If free GPU memory is insufficient for the
requested memory utilization
RuntimeError: If device type is not supported
"""
if self.device_config.device.type == "cuda":
# This env var set by Ray causes exceptions with graph building.
os.environ.pop("NCCL_ASYNC_ERROR_HANDLING", None)
+17
View File
@@ -13,7 +13,24 @@ from vllm_omni.worker.gpu_diffusion_model_runner import GPUDiffusionModelRunner
class GPUDiffusionWorker(GPUWorker):
"""GPU worker for diffusion-based omni model stages.
Extends the base GPUWorker to initialize and manage diffusion model
runners for non-autoregressive generation stages (e.g., image or
audio generation stages).
"""
def init_device(self):
"""Initialize the GPU device and diffusion model runner.
Sets up CUDA device, initializes distributed environment,
sets random seed, and creates a GPUDiffusionModelRunner instance.
Raises:
ValueError: If free GPU memory is insufficient for the
requested memory utilization
RuntimeError: If device type is not supported
"""
if self.device_config.device.type == "cuda":
# This env var set by Ray causes exceptions with graph building.
os.environ.pop("NCCL_ASYNC_ERROR_HANDLING", None)
+19
View File
@@ -30,7 +30,26 @@ logger = init_logger(__name__)
class OmniGPUModelRunner(GPUModelRunner):
"""GPU model runner for omni models with M-RoPE support.
Extends the base GPUModelRunner to handle multimodal rotary position
embeddings (M-RoPE) for processing image, video, and audio inputs
with proper positional encoding.
"""
def _init_mrope_positions(self, req_state: CachedRequestState):
"""Initialize M-RoPE positions for multimodal inputs.
Extracts multimodal feature metadata (image grids, video grids,
audio features) and computes M-RoPE positions for proper positional
encoding of multimodal tokens.
Args:
req_state: Cached request state containing multimodal features
Raises:
AssertionError: If the model does not support M-RoPE
"""
image_grid_thw = []
video_grid_thw = []
second_per_grid_ts = []