[Entrypoints] Support Online Serving for Diffusion-only Models (#259)

Signed-off-by: Chenguang ZHENG <645327136@qq.com>
Signed-off-by: yinpe <11810305@mail.sustech.edu.cn>
Co-authored-by: yinpe <11810305@mail.sustech.edu.cn>
This commit is contained in:
Chenguang Zhengandyinpe authored and GitHub committed 2025-12-17 17:40:45 +08:00
1 parent 8722c6374c
commit acf66ee2cc
19 files changed
+2506 -20

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
OpenAI-compatible API entrypoints for vLLM-Omni.
Provides:
- omni_run_server: Main server entry point (auto-detects model type)
- omni_run_diffusion_server: Server for diffusion models
- OmniOpenAIServingChat: Unified chat completion handler for both LLM and diffusion models
"""
from vllm_omni.entrypoints.openai.api_server import (
build_async_diffusion,
build_async_omni,
omni_diffusion_init_app_state,
omni_init_app_state,
omni_run_diffusion_server,
omni_run_server,
)
from vllm_omni.entrypoints.openai.serving_chat import OmniOpenAIServingChat
__all__ = [
# Server functions
"omni_run_server",
"omni_run_diffusion_server",
"build_async_omni",
"build_async_diffusion",
"omni_init_app_state",
"omni_diffusion_init_app_state",
# Serving classes
"OmniOpenAIServingChat",
]
+169 -3
View File
@@ -1,9 +1,11 @@
import json
import multiprocessing
import multiprocessing.forkserver as forkserver
import os
from argparse import Namespace
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import fields
from http import HTTPStatus
from typing import Any
@@ -38,6 +40,9 @@ from vllm.logger import init_logger
from vllm.transformers_utils.tokenizer import MistralTokenizer
from vllm.utils import decorate_logs
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.utils.hf_utils import is_diffusion_model
from vllm_omni.entrypoints.async_diffusion import AsyncOmniDiffusion
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.openai.serving_chat import OmniOpenAIServingChat
@@ -45,13 +50,73 @@ logger = init_logger(__name__)
async def omni_run_server(args, **uvicorn_kwargs) -> None:
"""Run a single-worker API server."""
"""Run a single-worker API server.
Automatically detects if the model is a diffusion model and routes
to the appropriate server implementation.
"""
# Add process-specific prefix to stdout and stderr.
decorate_logs("APIServer")
listen_address, sock = setup_server(args)
await omni_run_server_worker(listen_address, sock, args, **uvicorn_kwargs)
# Check if model is a diffusion model
if is_diffusion_model(args.model):
logger.info("Detected diffusion model, starting diffusion API server")
await omni_run_diffusion_server_worker(listen_address, sock, args, **uvicorn_kwargs)
else:
await omni_run_server_worker(listen_address, sock, args, **uvicorn_kwargs)
async def omni_run_diffusion_server(args, **uvicorn_kwargs) -> None:
"""Run a diffusion model API server."""
# Add process-specific prefix to stdout and stderr.
decorate_logs("DiffusionAPIServer")
listen_address, sock = setup_server(args)
await omni_run_diffusion_server_worker(listen_address, sock, args, **uvicorn_kwargs)
async def omni_run_diffusion_server_worker(listen_address, sock, args, **uvicorn_kwargs) -> None:
"""Run a diffusion model API server worker."""
# Load logging config for uvicorn if specified
log_config = load_log_config(args.log_config_file)
if log_config is not None:
uvicorn_kwargs["log_config"] = log_config
async with build_async_diffusion(args) as diffusion_engine:
app = build_app(args)
await omni_diffusion_init_app_state(diffusion_engine, app.state, args)
logger.info("Starting vLLM Diffusion API server on %s", listen_address)
shutdown_task = await serve_http(
app,
sock=sock,
enable_ssl_refresh=getattr(args, "enable_ssl_refresh", False),
host=args.host,
port=args.port,
log_level=args.uvicorn_log_level,
access_log=not getattr(args, "disable_uvicorn_access_log", False),
timeout_keep_alive=envs.VLLM_HTTP_TIMEOUT_KEEP_ALIVE,
ssl_keyfile=getattr(args, "ssl_keyfile", None),
ssl_certfile=getattr(args, "ssl_certfile", None),
ssl_ca_certs=getattr(args, "ssl_ca_certs", None),
ssl_cert_reqs=getattr(args, "ssl_cert_reqs", 0),
h11_max_incomplete_event_size=getattr(args, "h11_max_incomplete_event_size", None),
h11_max_header_count=getattr(args, "h11_max_header_count", None),
**uvicorn_kwargs,
)
# NB: Await server shutdown only after the backend context is exited
try:
await shutdown_task
finally:
sock.close()
async def omni_run_server_worker(listen_address, sock, args, client_config=None, **uvicorn_kwargs) -> None:
@@ -147,6 +212,60 @@ async def build_async_omni(
yield async_omni
@asynccontextmanager
async def build_async_diffusion(
args: Namespace,
**kwargs: Any,
) -> AsyncIterator[AsyncOmniDiffusion]:
"""Build an AsyncOmniDiffusion instance from command-line arguments.
Creates an async context manager that yields an AsyncOmniDiffusion
instance configured from the provided arguments.
Args:
args: Parsed command-line arguments containing model and configuration
**kwargs: Additional keyword arguments passed to AsyncOmniDiffusion
Yields:
AsyncOmniDiffusion instance ready for use
"""
diffusion_engine: AsyncOmniDiffusion | None = None
try:
# Build diffusion kwargs by extracting matching OmniDiffusionConfig fields from args
config_field_names = {f.name for f in fields(OmniDiffusionConfig)}
diffusion_kwargs: dict[str, Any] = {"model": args.model}
for field_name in config_field_names:
if not hasattr(args, field_name):
continue
value = getattr(args, field_name)
if value is None:
continue
# Special handling for cache_config JSON string
if field_name == "cache_config" and isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError as e:
logger.warning(f"Failed to parse cache_config JSON: {e}")
continue
diffusion_kwargs[field_name] = value
diffusion_kwargs.update(kwargs)
logger.info(f"diffusion_kwargs: {diffusion_kwargs}")
logger.info(
"Building AsyncOmniDiffusion with model=%s, num_gpus=%s",
args.model,
diffusion_kwargs.get("num_gpus", 1),
)
diffusion_engine = AsyncOmniDiffusion(**diffusion_kwargs)
yield diffusion_engine
finally:
if diffusion_engine:
diffusion_engine.shutdown()
@asynccontextmanager
async def build_async_omni_from_stage_config(
args: Namespace,
@@ -318,6 +437,49 @@ def Omnichat(request: Request) -> OmniOpenAIServingChat | None:
return request.app.state.openai_serving_chat
async def omni_diffusion_init_app_state(
diffusion_engine: AsyncOmniDiffusion,
state: State,
args: Namespace,
) -> None:
"""Initialize the FastAPI application state for diffusion model API server.
Sets up the application state with diffusion model information and
chat completion handler for image generation via /v1/chat/completions.
Args:
diffusion_engine: AsyncOmniDiffusion engine instance
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:
served_model_names = [args.model]
model_name = served_model_names[0] if served_model_names else args.model
state.diffusion_engine = diffusion_engine
state.log_stats = not getattr(args, "disable_log_stats", False)
# Initialize chat handler with diffusion engine (uses /v1/chat/completions endpoint)
# Note: Request-level parameters (num_inference_steps, guidance_scale, seed, height, width, etc.)
# are passed per-request via the API, not as server defaults
state.openai_serving_chat = OmniOpenAIServingChat.for_diffusion(
diffusion_engine=diffusion_engine,
model_name=model_name,
)
# Set other handlers to None for diffusion-only mode
state.engine_client = None
state.vllm_config = None
state.enable_server_load_tracking = getattr(args, "enable_server_load_tracking", False)
state.server_load_metrics = 0
logger.info("Diffusion API server initialized for model: %s", model_name)
@router.post(
"/v1/chat/completions",
dependencies=[Depends(validate_json_request)],
@@ -337,9 +499,13 @@ async def create_chat_completion(request: ChatCompletionRequest, raw_request: Re
try:
generator = await handler.create_chat_completion(request, raw_request)
except Exception as e:
logger.exception("Chat completion failed: %s", e)
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e)) from e
if isinstance(generator, ErrorResponse):
return JSONResponse(content=generator.model_dump(), status_code=generator.error.code)
return JSONResponse(
content=generator.model_dump(), status_code=generator.code if hasattr(generator, "code") else 400
)
elif isinstance(generator, ChatCompletionResponse):
return JSONResponse(content=generator.model_dump())
+385 -1
View File
@@ -6,10 +6,11 @@ import uuid
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Sequence
from datetime import datetime, timedelta, timezone
from io import BytesIO
from typing import Any
from typing import TYPE_CHECKING, Any, Optional
import jinja2
from fastapi import Request
from PIL import Image
from pydantic import TypeAdapter
try:
@@ -71,10 +72,52 @@ from vllm.utils import as_list
from vllm_omni.entrypoints.chat_utils import parse_chat_messages_futures
from vllm_omni.outputs import OmniRequestOutput
if TYPE_CHECKING:
from vllm_omni.entrypoints.async_diffusion import AsyncOmniDiffusion
logger = init_logger(__name__)
class OmniOpenAIServingChat(OpenAIServingChat):
"""OpenAI-compatible chat serving for both LLM and Diffusion models.
This class extends OpenAIServingChat to support:
- Standard LLM chat completions
- Diffusion model image generation via chat interface
For diffusion mode, use the `for_diffusion` class method to create an instance.
"""
# Diffusion mode attributes
_diffusion_mode: bool = False
_diffusion_engine: Optional["AsyncOmniDiffusion"] = None
_diffusion_model_name: str = ""
@classmethod
def for_diffusion(
cls,
diffusion_engine: "AsyncOmniDiffusion",
model_name: str,
) -> "OmniOpenAIServingChat":
"""Create a chat serving instance for diffusion models.
Args:
diffusion_engine: The async diffusion engine
model_name: Name of the model being served
Returns:
OmniOpenAIServingChat instance configured for diffusion mode
Note:
Request-level parameters (num_inference_steps, guidance_scale, seed,
height, width, num_frames, fps, etc.) are passed per-request via the API.
"""
instance = cls.__new__(cls)
instance._diffusion_mode = True
instance._diffusion_engine = diffusion_engine
instance._diffusion_model_name = model_name
return instance
async def create_chat_completion(
self,
request: ChatCompletionRequest,
@@ -86,7 +129,14 @@ class OmniOpenAIServingChat(OpenAIServingChat):
See https://platform.openai.com/docs/api-reference/chat/create
for the API specification. This API mimics the OpenAI
Chat Completion API.
For diffusion models, this generates images and returns them
in a chat completion response format.
"""
# Handle diffusion mode
if self._diffusion_mode:
return await self._create_diffusion_chat_completion(request, raw_request)
error_check_ret = await self._check_model(request)
if error_check_ret is not None:
logger.error("Error with model %s", error_check_ret)
@@ -438,6 +488,8 @@ class OmniOpenAIServingChat(OpenAIServingChat):
) = self._create_text_choice(request, omni_outputs, tokenizer, conversation, role)
elif omni_outputs.final_output_type == "audio":
choices_data = self._create_audio_choice(omni_outputs, role)
elif omni_outputs.final_output_type == "image":
choices_data = self._create_image_choice(omni_outputs, role)
else:
logger.warning(f"Unsupported final output type: {omni_outputs.final_output_type}")
continue
@@ -780,3 +832,335 @@ class OmniOpenAIServingChat(OpenAIServingChat):
)
choices.append(choice_data)
return choices
def _create_image_choice(self, omni_outputs: OmniRequestOutput, role: str):
"""Create chat completion response choices for image output.
Converts image tensor or PIL Image output from diffusion models
into base64-encoded image data for API response.
Args:
omni_outputs: Output containing image data from diffusion stage
role: The role for the response message (e.g., "assistant")
Returns:
List of ChatCompletionResponseChoice with image content
"""
from PIL import Image
choices: list[ChatCompletionResponseChoice] = []
final_res = omni_outputs.request_output
# Handle different image output formats
images = []
# First check omni_outputs.images directly (for diffusion mode via from_diffusion)
if omni_outputs.images:
images = omni_outputs.images
# Fall back to request_output for pipeline mode
elif final_res is not None:
if hasattr(final_res, "multimodal_output") and final_res.multimodal_output:
image_data = final_res.multimodal_output.get("image")
if image_data is not None:
if isinstance(image_data, Image.Image):
images.append(image_data)
elif hasattr(image_data, "cpu"): # Tensor
import numpy as np
# Convert tensor to PIL Image
img_array = image_data.float().detach().cpu().numpy()
# Handle different tensor formats (CHW -> HWC)
if img_array.ndim == 3 and img_array.shape[0] in [1, 3, 4]:
img_array = np.transpose(img_array, (1, 2, 0))
# Normalize to 0-255
if img_array.max() <= 1.0:
img_array = (img_array * 255).astype(np.uint8)
else:
img_array = img_array.astype(np.uint8)
# Handle grayscale
if img_array.ndim == 2:
images.append(Image.fromarray(img_array, mode="L"))
elif img_array.shape[-1] == 1:
images.append(Image.fromarray(img_array.squeeze(-1), mode="L"))
elif img_array.shape[-1] == 3:
images.append(Image.fromarray(img_array, mode="RGB"))
elif img_array.shape[-1] == 4:
images.append(Image.fromarray(img_array, mode="RGBA"))
elif hasattr(final_res, "images") and final_res.images:
images = final_res.images
# Convert images to base64
image_contents = []
for img in images:
with BytesIO() as buffer:
img.save(buffer, format="PNG")
img_bytes = buffer.getvalue()
img_base64 = base64.b64encode(img_bytes).decode("utf-8")
image_contents.append(
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{img_base64}",
},
}
)
# Create message content
if len(image_contents) == 1:
content = image_contents
elif len(image_contents) > 1:
content = image_contents
else:
content = [{"type": "text", "text": "Image generation completed but no images were produced."}]
# Create response choice
choice_data = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role=role, content=content),
logprobs=None,
finish_reason="stop",
stop_reason=None,
)
choices.append(choice_data)
return choices
# ==================== Diffusion Mode Methods ====================
async def _create_diffusion_chat_completion(
self,
request: ChatCompletionRequest,
raw_request: Request | None = None,
) -> ChatCompletionResponse | ErrorResponse:
"""Generate images via chat completion interface for diffusion models.
Args:
request: Chat completion request
raw_request: Raw FastAPI request object
Returns:
ChatCompletionResponse with generated images or ErrorResponse
"""
try:
request_id = f"chatcmpl-{uuid.uuid4().hex[:16]}"
created_time = int(time.time())
# Convert messages to dict format
messages = []
for msg in request.messages:
if hasattr(msg, "model_dump"):
messages.append(msg.model_dump())
elif isinstance(msg, dict):
messages.append(msg)
else:
messages.append({"role": getattr(msg, "role", "user"), "content": getattr(msg, "content", "")})
# Extract prompt and images from messages
prompt, reference_images = self._extract_diffusion_prompt_and_images(messages)
if not prompt:
return self._create_error_response("No text prompt found in messages")
# Extract generation parameters from extra_body (preferred)
# Reference: text_to_image.py and text_to_video.py for supported parameters
extra_body = getattr(request, "extra_body", None) or {}
# Parse size if provided (supports "1024x1024" format)
height = extra_body.get("height")
width = extra_body.get("width")
if "size" in extra_body:
try:
size_str = extra_body["size"]
if isinstance(size_str, str) and "x" in size_str.lower():
w, h = size_str.lower().split("x")
width, height = int(w), int(h)
except ValueError:
logger.warning("Invalid size format: %s", extra_body.get("size"))
# Get request parameters from extra_body
# Text-to-image parameters (ref: text_to_image.py)
num_inference_steps = extra_body.get("num_inference_steps", 50)
guidance_scale = extra_body.get("guidance_scale", 7.5)
true_cfg_scale = extra_body.get("true_cfg_scale") # Qwen-Image specific
seed = extra_body.get("seed")
negative_prompt = extra_body.get("negative_prompt")
num_outputs_per_prompt = extra_body.get("num_outputs_per_prompt", 1)
# Text-to-video parameters (ref: text_to_video.py)
num_frames = extra_body.get("num_frames")
guidance_scale_2 = extra_body.get("guidance_scale_2") # For video high-noise CFG
logger.info(
"Diffusion chat request %s: prompt=%r, ref_images=%d, params=%s",
request_id,
prompt[:50] + "..." if len(prompt) > 50 else prompt,
len(reference_images),
{k: v for k, v in extra_body.items() if v is not None},
)
# Decode reference images if provided
pil_images: list[Image.Image] = []
for img_b64 in reference_images:
try:
img_bytes = base64.b64decode(img_b64)
pil_images.append(Image.open(BytesIO(img_bytes)))
except Exception as e:
logger.warning("Failed to decode reference image: %s", e)
# Build generation kwargs
gen_kwargs: dict[str, Any] = {
"prompt": prompt,
"request_id": request_id,
"num_inference_steps": num_inference_steps,
"guidance_scale": guidance_scale,
"height": height,
"width": width,
"negative_prompt": negative_prompt,
"num_outputs_per_prompt": num_outputs_per_prompt,
"seed": seed,
}
# Add Qwen-Image specific parameter
if true_cfg_scale is not None:
gen_kwargs["true_cfg_scale"] = true_cfg_scale
# Add video generation parameters if set
if num_frames is not None:
gen_kwargs["num_frames"] = num_frames
if guidance_scale_2 is not None:
gen_kwargs["guidance_scale_2"] = guidance_scale_2
# Add reference image if provided
if pil_images:
gen_kwargs["pil_image"] = pil_images[0]
# Generate image
result = await self._diffusion_engine.generate(**gen_kwargs)
# Convert images to base64 content
image_contents: list[dict[str, Any]] = []
for img in result.images:
with BytesIO() as buffer:
img.save(buffer, format="PNG")
img_bytes = buffer.getvalue()
img_base64 = base64.b64encode(img_bytes).decode("utf-8")
image_contents.append(
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{img_base64}",
},
}
)
# Build response
if not image_contents:
content = "Image generation completed but no images were produced."
else:
content = image_contents
# Use model_construct to bypass validation for multimodal content
# (ChatMessage.content only accepts str, but we need list for images)
message = ChatMessage.model_construct(role="assistant", content=content)
choice = ChatCompletionResponseChoice.model_construct(
index=0,
message=message,
finish_reason="stop",
logprobs=None,
stop_reason=None,
)
response = ChatCompletionResponse(
id=request_id,
created=created_time,
model=self._diffusion_model_name,
choices=[choice],
usage=UsageInfo(
prompt_tokens=len(prompt.split()),
completion_tokens=1,
total_tokens=len(prompt.split()) + 1,
),
)
logger.info(
"Diffusion chat completed for request %s: %d images",
request_id,
len(result.images),
)
return response
except Exception as e:
logger.exception("Diffusion chat completion failed: %s", e)
return self._create_error_response(
f"Image generation failed: {str(e)}",
status_code=500,
)
def _extract_diffusion_prompt_and_images(
self,
messages: list[dict[str, Any]],
) -> tuple[str, list[str]]:
"""Extract text prompt and base64 images from chat messages.
Args:
messages: List of chat messages
Returns:
Tuple of (prompt_text, list_of_base64_images)
"""
prompt_parts: list[str] = []
images: list[str] = []
for message in messages:
role = message.get("role", "")
if role != "user":
continue
content = message.get("content", "")
# String content
if isinstance(content, str):
prompt_parts.append(content)
continue
# List of content items
if isinstance(content, list):
for item in content:
if isinstance(item, str):
prompt_parts.append(item)
elif isinstance(item, dict):
# Handle {"type": "text", "text": "..."} format
if item.get("type") == "text":
prompt_parts.append(item.get("text", ""))
# Handle {"text": "..."} format
elif "text" in item and "type" not in item:
prompt_parts.append(item["text"])
# Handle {"type": "image_url", "image_url": {"url": "..."}}
elif item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image"):
try:
_, b64_data = url.split(",", 1)
images.append(b64_data)
except ValueError:
logger.warning("Invalid data URL format")
# Handle {"image": "base64..."} format
elif "image" in item:
images.append(item["image"])
prompt = " ".join(prompt_parts).strip()
return prompt, images
def _create_error_response(
self,
message: str,
err_type: str = "BadRequestError",
status_code: int = 400,
) -> ErrorResponse:
"""Create an error response following OpenAI error format."""
return ErrorResponse(
message=message,
type=err_type,
code=status_code,
)