[Perf] GLM Image (#920)

Signed-off-by: JaredforReal <w13431838023@gmail.com>
Signed-off-by: Jared Wen <w13431838023@gmail.com>
Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: 汪志鹏 <wangzhipeng628@gmail.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-02-27 10:29:14 +08:00
1 parent f6ed1bc4e7
commit 4146095623
25 files changed
+5182 -221

No files matched your search

+13 -4
View File
@@ -47,8 +47,9 @@ class OmniDiffusion:
if engine_input_source is not None:
self.od_config.omni_kv_config.setdefault("engine_input_source", engine_input_source)
# Detect model class and load config
# Diffusers-style models expose `model_index.json` with `_class_name`.
# Non-diffusers models (e.g. Bagel, NextStep) only have `config.json`,
# Non-diffusers models (e.g. Bagel, NextStep, GLM-Image) only have `config.json`,
# so we fall back to reading that and mapping model_type manually.
try:
config_dict = get_hf_file_to_dict(
@@ -71,6 +72,7 @@ class OmniDiffusion:
if cfg is None:
raise ValueError(f"Could not find config.json or model_index.json for model {od_config.model}")
# Map model_type or architecture to pipeline class
model_type = cfg.get("model_type")
architectures = cfg.get("architectures") or []
# Bagel/NextStep models don't have a model_index.json, so we set the pipeline class name manually
@@ -83,10 +85,17 @@ class OmniDiffusion:
od_config.model_class_name = "NextStep11Pipeline"
od_config.tf_model_config = TransformerConfig()
od_config.update_multimodal_support()
elif model_type == "glm-image" or "GlmImageForConditionalGeneration" in architectures:
pipeline_class = "GlmImagePipeline"
elif architectures and len(architectures) == 1:
od_config.model_class_name = architectures[0]
else:
raise
pipeline_class = architectures[0]
if pipeline_class is None:
raise ValueError(f"Unknown model type: {model_type}, architectures: {architectures}")
od_config.model_class_name = pipeline_class
od_config.tf_model_config = TransformerConfig()
od_config.update_multimodal_support()
self.engine: DiffusionEngine = DiffusionEngine.make_engine(od_config)
+11 -3
View File
@@ -44,6 +44,7 @@ from vllm_omni.entrypoints.omni_llm import OmniLLM
from vllm_omni.entrypoints.stage_utils import (
SHUTDOWN_TASK,
OmniStageTaskType,
_resolve_model_tokenizer_paths,
_to_dict,
is_profiler_task,
maybe_dump_to_shm,
@@ -251,7 +252,7 @@ class OmniStage:
"""
def __init__(self, stage_config: Any, stage_init_timeout: int = 300):
logger.info(f"[OmniStage] stage_config: {stage_config}")
logger.debug(f"[OmniStage] stage_config: {stage_config}")
self.stage_config = stage_config
self.engine = None
self.async_engine = None
@@ -708,6 +709,9 @@ def _stage_worker(
if stage_type != "diffusion":
_resolve_worker_cls(engine_args)
# Handle non-standard model directory structures (e.g., tokenizer in root, model in subdir)
model = _resolve_model_tokenizer_paths(model, engine_args)
# Resolve ZMQ queue endpoints if needed
zmq_ctx = None
if isinstance(in_q, str) or isinstance(out_q, str):
@@ -933,8 +937,9 @@ def _stage_worker(
_rx_bytes_by_rid[rid] = int(_rx_metrics.get("rx_transfer_bytes", 0))
batch_request_ids.append(rid)
if isinstance(ein, (str, dict)):
# Types like OmniTextPrompt, TextPrompt are TypedDict, essentially dict and enters this branch
if isinstance(ein, (dict, str)):
# For diffusion stage-0, ein might be a string prompt directly
batch_engine_inputs.append(ein)
elif isinstance(ein, Sequence):
batch_engine_inputs.extend(ein)
@@ -1108,6 +1113,9 @@ async def _stage_worker_async(
final_output = stage_payload.get("final_output", False)
final_output_type = stage_payload.get("final_output_type", None)
# Handle non-standard model directory structures (e.g., tokenizer in root, model in subdir)
model = _resolve_model_tokenizer_paths(model, engine_args)
if stage_type != "diffusion":
_resolve_worker_cls(engine_args)
@@ -274,6 +274,80 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
output_modalities if output_modalities is not None else self.engine_client.output_modalities
)
# Omni multistage image generation: Stage-0 (AR) should receive a clean
# text prompt (and optional conditioning image/size) so the model's own
# processor can construct the correct inputs.
# If we pass pre-tokenized chat-template ids, GLM-Image can become
# effectively unconditioned and produce nonsense images.
if request.modalities and ("image" in request.modalities):
try:
messages_as_dicts: list[dict[str, Any]] = []
for msg in request.messages:
if hasattr(msg, "model_dump"):
messages_as_dicts.append(msg.model_dump())
elif isinstance(msg, dict):
messages_as_dicts.append(msg)
else:
messages_as_dicts.append(
{
"role": getattr(msg, "role", "user"),
"content": getattr(msg, "content", ""),
}
)
extracted_prompt, reference_images = self._extract_diffusion_prompt_and_images(messages_as_dicts)
if not extracted_prompt:
return self.create_error_response("No text prompt found in messages")
extra_body = getattr(request, "extra_body", None) or {}
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 Exception:
pass
negative_prompt = extra_body.get("negative_prompt")
engine_prompt_image: dict[str, Any] | None = None
if reference_images:
# Best-effort decode first reference image for i2i.
try:
img_bytes = base64.b64decode(reference_images[0])
img = Image.open(BytesIO(img_bytes))
engine_prompt_image = {"image": img}
except Exception:
engine_prompt_image = None
# Override the prompts produced by chat-template preprocessing.
tprompt: OmniTextPrompt = {"prompt": extracted_prompt}
if negative_prompt is not None:
tprompt["negative_prompt"] = negative_prompt
# GLM-Image's _call_hf_processor expects target_h/target_w in mm_processor_kwargs
mm_processor_kwargs: dict[str, Any] = {}
if height is not None:
mm_processor_kwargs["target_h"] = height
if width is not None:
mm_processor_kwargs["target_w"] = width
if mm_processor_kwargs:
tprompt["mm_processor_kwargs"] = mm_processor_kwargs
if engine_prompt_image is not None:
tprompt["multi_modal_data"] = engine_prompt_image
engine_prompts = [tprompt]
# Store height/width for applying to diffusion stage sampling params later
_image_gen_height = height
_image_gen_width = width
except Exception as e:
logger.warning("Failed to build image-generation prompt for omni multistage: %s", e)
_image_gen_height = None
_image_gen_width = None
else:
_image_gen_height = None
_image_gen_width = None
# Schedule the request and get the result generator.
generators: list[AsyncGenerator[RequestOutput, None]] = []
try:
@@ -284,6 +358,15 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
# Use standard OpenAI API parameters for comprehension stage
sampling_params_list = self._build_sampling_params_list_from_request(request)
# Apply user-specified height/width to diffusion stage(s) for image generation
if _image_gen_height is not None or _image_gen_width is not None:
for idx, sp in enumerate(sampling_params_list):
# Diffusion stages typically have height/width attributes
if hasattr(sp, "height") and _image_gen_height is not None:
sp.height = _image_gen_height
if hasattr(sp, "width") and _image_gen_width is not None:
sp.width = _image_gen_width
self._log_inputs(
request_id,
engine_prompt,
@@ -420,6 +503,35 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
request=request
)
# Preserve a clean text prompt for downstream stages (e.g., GLM-Image diffusion).
# For /v1/chat/completions, `request_prompt` is often the rendered chat template.
# Diffusion models generally want the raw user caption instead.
output_modalities = getattr(self.engine_client, "output_modalities", None)
if output_modalities and ("image" in output_modalities):
messages_as_dicts: list[dict[str, Any]] = []
for msg in messages:
if hasattr(msg, "model_dump"):
messages_as_dicts.append(msg.model_dump())
elif isinstance(msg, dict):
messages_as_dicts.append(msg)
else:
messages_as_dicts.append(
{
"role": getattr(msg, "role", "user"),
"content": getattr(msg, "content", ""),
}
)
extracted_prompt, _ = self._extract_diffusion_prompt_and_images(messages_as_dicts)
if extracted_prompt:
engine_prompt["prompt"] = extracted_prompt
mm_processor_kwargs = getattr(request, "mm_processor_kwargs", None)
if mm_processor_kwargs is not None:
engine_prompt["mm_processor_kwargs"] = mm_processor_kwargs
if hasattr(request, "cache_salt") and request.cache_salt is not None:
engine_prompt["cache_salt"] = request.cache_salt
return conversation, [engine_prompt]
def _to_sampling_params_list(self, sampling_params_list: list[dict]) -> list[SamplingParams]:
+38
View File
@@ -302,3 +302,41 @@ def _to_dict(x: Any) -> dict[str, Any]:
return dict(x)
except Exception:
return {}
def _resolve_model_tokenizer_paths(
model: str,
engine_args: dict,
) -> str:
"""Resolve model and tokenizer paths for non-standard directory structures.
Some models (e.g., GLM-Image) have tokenizer in root and model in subdirectory.
This function handles model_subdir and tokenizer_subdir engine_args.
Args:
model: Base model path
engine_args: Engine arguments (modified in-place to remove subdir args
and set tokenizer if needed)
Returns:
Resolved model path (may be subdirectory of original)
"""
import os
model_subdir = engine_args.pop("model_subdir", None)
tokenizer_subdir = engine_args.pop("tokenizer_subdir", None)
base_model_path = model
if model_subdir:
model = os.path.join(model, model_subdir)
logger.info(f"Using model subdirectory: {model}")
if tokenizer_subdir is not None:
tokenizer_path = os.path.join(base_model_path, tokenizer_subdir) if tokenizer_subdir else base_model_path
engine_args["tokenizer"] = tokenizer_path
logger.info(f"Using tokenizer from: {tokenizer_path}")
elif model_subdir and "tokenizer" not in engine_args:
engine_args["tokenizer"] = base_model_path
logger.info(f"Using tokenizer from base model path: {base_model_path}")
return model