Benchmark and Bugfix for GLM-Image (#3024)

Signed-off-by: JaredforReal <w13431838023@gmail.com>
Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
Jared WenandHongsheng Liu authored and GitHub committed 2026-04-25 20:49:19 +08:00
1 parent 6b52db9e2b
commit 6e35bfbbae
18 files changed
+1836 -381

No files matched your search

+5
View File
@@ -477,6 +477,11 @@ class OmniServeCommand(CLISubcommand):
action="store_true",
help="Enable diffusion pipeline profiler to display stage durations.",
)
omni_config_group.add_argument(
"--enable-ar-profiler",
action="store_true",
help="Enable AR stage profiler to include AR stage timing in stage_durations.",
)
# Stash via type(self) so the docs hook (which execs this function in a
# sandboxed globals dict via ``DummySelf``) doesn't fail on a NameError.
type(self)._parser = serve_parser
+25
View File
@@ -124,6 +124,7 @@ class OmniBase(PDDisaggregationMixin):
stage_init_timeout = kwargs.pop("stage_init_timeout", 300)
init_timeout = kwargs.pop("init_timeout", 600)
log_stats = kwargs.pop("log_stats", False)
self._enable_ar_profiler = kwargs.pop("enable_ar_profiler", False)
# NOTE: read-only lookup — must NOT pop. Popping here drops the key
# before it reaches ``StageConfigFactory._create_from_registry``, so
# ``--no-async-chunk`` (``async_chunk=False``) silently fails to
@@ -375,6 +376,30 @@ class OmniBase(PDDisaggregationMixin):
engine_outputs = result.get("engine_outputs")
stage_durations = getattr(result["engine_outputs"], "stage_durations", {})
peak_memory_mb = getattr(result["engine_outputs"], "peak_memory_mb", 0.0)
# Merge AR stage timing from OrchestratorAggregator.stage_events
if self._enable_ar_profiler:
ar_events = metrics.stage_events.get(str(req_id), [])
for evt in ar_events:
if evt.stage_id != stage_id:
stage_durations[f"ar_stage_{evt.stage_id}"] = evt.stage_gen_time_ms / 1000.0
# Merge pipeline timings from Orchestrator into stage_durations
_m = result.get("metrics")
if _m is not None and hasattr(_m, "pipeline_timings") and _m.pipeline_timings:
for key, value in _m.pipeline_timings.items():
if key not in stage_durations:
stage_durations[key] = value
# Merge per-stage gen times into stage_durations
for evt in metrics.stage_events.get(str(req_id), []):
key = f"stage_{evt.stage_id}_gen_ms"
if key not in stage_durations:
stage_durations[key] = evt.stage_gen_time_ms
# Current stage gen time (not yet in stage_events at this point)
if _m is not None:
stage_durations.setdefault(f"stage_{stage_id}_gen_ms", _m.stage_gen_time_ms)
finished = engine_outputs.finished
submit_ts = result.get("stage_submit_ts")
+75 -10
View File
@@ -1793,20 +1793,85 @@ async def edit_images(
_update_if_not_none(gen_params, "layers", layers)
_update_if_not_none(gen_params, "resolution", resolution)
# 4. Generate images using AsyncOmni (multi-stage mode)
# 4. Generate images
request_id = f"img_edit-{random_uuid()}"
raw_request.state.request_metadata = RequestResponseMetadata(request_id=request_id)
logger.info(f"Generating {n} image(s) {size_str}")
result = await _generate_with_async_omni(
engine_client=engine_client,
gen_params=gen_params,
stage_configs=stage_configs,
prompt=prompt,
request_id=request_id,
)
# 5. Extract images from result
images = _extract_images_from_result(result)
if len(stage_configs) > 1:
# Multi-stage pipeline (e.g. GLM-Image AR+Diffusion): route through
# the chat handler so the AR stage gets correct max_tokens and
# target_h/w (same path as /v1/images/generations).
chat_handler = getattr(raw_request.app.state, "openai_serving_chat", None)
if chat_handler is None:
raise HTTPException(
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
detail="openai_serving_chat is not initialized for multi-stage image editing.",
)
# Encode input images to base64 for generate_diffusion_images.
import base64
import io as _io
ref_b64_list: list[str] = []
for _img in pil_images:
buf = _io.BytesIO()
_img.save(buf, format="PNG")
ref_b64_list.append(base64.b64encode(buf.getvalue()).decode())
effective_seed = seed if seed is not None else random.randint(0, MAX_UINT32_SEED)
extra_body: dict[str, Any] = {
"seed": effective_seed,
"num_outputs_per_prompt": n,
}
if width is not None:
extra_body["width"] = width
if height is not None:
extra_body["height"] = height
if negative_prompt is not None:
extra_body["negative_prompt"] = negative_prompt
if num_inference_steps is not None:
extra_body["num_inference_steps"] = num_inference_steps
if guidance_scale is not None:
extra_body["guidance_scale"] = guidance_scale
if strength is not None:
extra_body["strength"] = strength
if true_cfg_scale is not None:
extra_body["true_cfg_scale"] = true_cfg_scale
if layers is not None:
extra_body["layers"] = layers
if resolution is not None:
extra_body["resolution"] = resolution
if lora is not None:
# Validate LoRA, then pass through.
lora_dict = _get_lora_from_json_str(lora)
_parse_lora_request(lora_dict)
extra_body["lora"] = lora_dict
prompt_text = prompt.get("prompt", "")
generation_result = await chat_handler.generate_diffusion_images(
prompt=prompt_text,
extra_body=extra_body,
reference_images=ref_b64_list,
request_id=request_id,
)
if isinstance(generation_result, ErrorResponse):
raise HTTPException(
status_code=generation_result.error.code if generation_result.error else 400,
detail=generation_result.message,
)
images, _, _ = generation_result
else:
# Single-stage diffusion: use the direct path.
result = await _generate_with_async_omni(
engine_client=engine_client,
gen_params=gen_params,
stage_configs=stage_configs,
prompt=prompt,
request_id=request_id,
)
images = _extract_images_from_result(result)
logger.info(f"Successfully generated {len(images)} image(s)")
# Encode images to base64
+29 -90
View File
@@ -705,8 +705,9 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
Starts with YAML defaults and only overrides fields that the user
explicitly provided (non-None values) in the request.
For GLM-Image AR stage, if max_tokens is not in YAML and user provides
height/width in extra_body, computes max_tokens dynamically.
For models needing spatial metadata (e.g. GLM-Image), target_h/w is
injected into extra_args so the runner can build M-RoPE position grids.
max_tokens is NOT computed dynamically — it uses the deploy YAML default.
Args:
default_params: Default SamplingParams from stage config YAML.
@@ -736,36 +737,13 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
extra_body = getattr(request, "extra_body", {}) or {}
height, width = self._resolve_height_width_from_extra_body(extra_body)
# Best-effort mode detection from user messages.
# i2i requests include at least one reference image in message content.
_, reference_images = self._extract_diffusion_prompt_and_images_from_messages(request.messages)
ref_image_count = len(reference_images)
is_img2img = ref_image_count > 0
if height is not None and width is not None:
try:
from vllm_omni.model_executor.stage_input_processors.glm_image import compute_max_tokens
max_tokens = getattr(explicit_fields, "max_tokens", None)
if max_tokens is None:
max_tokens = compute_max_tokens(int(height), int(width), is_i2i=is_img2img)
params.max_tokens = max_tokens
# Keep target size in stage-0 sampling params so runner/model can
# build deterministic M-RoPE grids for t2i (no MM features).
extra_args = dict(getattr(params, "extra_args", {}) or {})
extra_args["target_h"] = int(height)
extra_args["target_w"] = int(width)
params.extra_args = extra_args
except (ImportError, ValueError, TypeError) as e:
logger.warning(f"Failed to compute max_tokens: {e}, using default if available")
else:
logger.info(
"[SamplingParams] Skip dynamic max_tokens (height=%s, width=%s, mode=%s, ref_images=%s)",
height,
width,
"i2i" if is_img2img else "t2i",
ref_image_count,
)
# Keep target size in stage-0 sampling params so runner/model can
# build deterministic M-RoPE grids for t2i (no MM features).
extra_args = dict(getattr(params, "extra_args", {}) or {})
extra_args["target_h"] = int(height)
extra_args["target_w"] = int(width)
params.extra_args = extra_args
return params
@@ -2185,6 +2163,9 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
engine_prompt["mm_processor_kwargs"] = mm_processor_kwargs
if engine_prompt_data is not None:
engine_prompt["multi_modal_data"] = engine_prompt_data
# Provide multi_modal_uuids so that newer vLLM versions can
# validate multi_modal_data / multi_modal_uuids consistency.
engine_prompt["multi_modal_uuids"] = {k: [f"img-{k}-{i}"] for i, k in enumerate(engine_prompt_data)}
comprehension_idx = None
for idx, stage in enumerate(stage_configs):
@@ -2192,24 +2173,6 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
comprehension_idx = idx
break
is_glm_image_multistage = False
for stage_cfg in stage_configs:
if isinstance(stage_cfg, dict):
engine_args = stage_cfg.get("engine_args")
model_arch = stage_cfg.get("model_arch")
else:
engine_args = getattr(stage_cfg, "engine_args", None)
model_arch = getattr(stage_cfg, "model_arch", None)
if model_arch is None and engine_args is not None:
if isinstance(engine_args, dict):
model_arch = engine_args.get("model_arch")
else:
model_arch = getattr(engine_args, "model_arch", None)
if model_arch in {"GlmImageForConditionalGeneration", "GlmImagePipeline"}:
is_glm_image_multistage = True
break
sampling_params_list: list[Any] = []
for idx, stage_cfg in enumerate(stage_configs):
stage_type = get_stage_type(stage_cfg)
@@ -2233,6 +2196,18 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
):
default_stage_params.seed = seed
# Inject target_h/w into comprehension (AR) stage sampling params
# for models that need M-RoPE position pre-computation (e.g.
# GLM-Image). max_tokens is handled via the deploy YAML default
# (upper-bound ceiling) rather than computed dynamically here.
if comprehension_idx is not None and idx == comprehension_idx and height is not None and width is not None:
extra_args = getattr(default_stage_params, "extra_args", None)
if extra_args is None:
extra_args = {}
default_stage_params.extra_args = extra_args
extra_args["target_h"] = int(height)
extra_args["target_w"] = int(width)
if stage_type == "diffusion":
self._set_if_supported(
default_stage_params,
@@ -2258,25 +2233,6 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
default_stage_params.lora_scale = lora_scale
except Exception as e: # pragma: no cover - safeguard
logger.warning("Failed to parse LoRA request: %s", e)
elif (
is_glm_image_multistage
and comprehension_idx is not None
and idx == comprehension_idx
and isinstance(default_stage_params, SamplingParams)
and height is not None
and width is not None
):
from vllm_omni.model_executor.stage_input_processors.glm_image import compute_max_tokens
default_stage_params.max_tokens = compute_max_tokens(
int(height),
int(width),
is_i2i=bool(reference_images),
)
extra_args = dict(getattr(default_stage_params, "extra_args", {}) or {})
extra_args["target_h"] = int(height)
extra_args["target_w"] = int(width)
default_stage_params.extra_args = extra_args
sampling_params_list.append(default_stage_params)
@@ -2300,16 +2256,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
engine = self._diffusion_engine if self._diffusion_engine is not None else self.engine_client
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"))
height, width = self._resolve_height_width_from_extra_body(extra_body)
seed = extra_body.get("seed")
generator_device = extra_body.get("generator_device")
@@ -2341,6 +2288,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
guidance_scale_2=extra_body.get("guidance_scale_2"),
layers=extra_body.get("layers"),
resolution=extra_body.get("resolution"),
strength=extra_body.get("strength"),
)
if lora_body and isinstance(lora_body, dict):
@@ -2461,16 +2409,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
extra_body = request.model_extra 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"))
height, width = self._resolve_height_width_from_extra_body(extra_body)
# Get request parameters from extra_body.
# Avoid hardcoded defaults here — let each pipeline's forward()
@@ -2787,8 +2726,8 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
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
except ValueError:
logger.warning("Invalid size format: %s", extra_body.get("size"))
return height, width