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
@@ -10,6 +10,10 @@ async_chunk: false
stages:
# Stage 0: AR Model (GlmImageForConditionalGeneration)
# Generates prior_token_ids for conditioning the diffusion process.
# max_tokens is set to the theoretical maximum (2048x2048 t2i ≈ 4353
# tokens). The AR model stops naturally at EOS (16385) well before
# this ceiling at lower resolutions. Do NOT override max_tokens per
# request — the actual resolution is communicated via target_h/w.
- stage_id: 0
max_num_seqs: 1
gpu_memory_utilization: 0.6
@@ -21,6 +25,7 @@ stages:
top_p: 0.75
top_k: 16512
stop_token_ids: [16385]
max_tokens: 4353
seed: 42
detokenize: false
+17
View File
@@ -1032,6 +1032,7 @@ class AsyncOmniEngine:
original_prompt = prompt
stage_type = self.stage_metadata[0].get("stage_type")
_preprocess_ms = 0.0
if stage_type != "diffusion" and not isinstance(prompt, EngineCoreRequest):
# Inject global_request_id into the raw prompt.
if isinstance(prompt, dict):
@@ -1041,6 +1042,7 @@ class AsyncOmniEngine:
_inject_global_id(item, request_id)
# Full input processing (tokenization, multimodal, etc.)
_t_preprocess = time.perf_counter()
request = self.input_processor.process_inputs(
request_id=request_id,
prompt=prompt,
@@ -1054,6 +1056,7 @@ class AsyncOmniEngine:
data_parallel_rank=data_parallel_rank,
resumable=resumable,
)
_preprocess_ms = (time.perf_counter() - _t_preprocess) * 1000.0
# TODO (Peiqi): add this for Qwen3-TTS only. Other models don't have
# additional_information field in the prompt.
request = _upgrade_to_omni_request(request, prompt)
@@ -1090,6 +1093,8 @@ class AsyncOmniEngine:
"original_prompt": original_prompt,
"sampling_params_list": effective_sampling_params_list,
"final_stage_id": final_stage_id,
"preprocess_ms": _preprocess_ms,
"enqueue_ts": time.perf_counter(),
}
def _enqueue_cfg_companions(
@@ -1316,6 +1321,7 @@ class AsyncOmniEngine:
"num_weight_load_threads": kwargs.get("num_weight_load_threads", 4),
"quantization": kwargs.get("quantization", None),
"enable_diffusion_pipeline_profiler": kwargs.get("enable_diffusion_pipeline_profiler", False),
"enable_ar_profiler": kwargs.get("enable_ar_profiler", False),
**(
{
"profiler_config": asdict(kwargs["profiler_config"])
@@ -1458,6 +1464,17 @@ class AsyncOmniEngine:
or cfg.engine_args.quantization_config is None
):
cfg.engine_args.quantization_config = quantization_config
# Inject profiler flags for diffusion stages
for profiler_key in (
"enable_diffusion_pipeline_profiler",
"enable_ar_profiler",
):
val = kwargs.get(profiler_key)
if val:
if not hasattr(cfg.engine_args, profiler_key) or not getattr(
cfg.engine_args, profiler_key, False
):
setattr(cfg.engine_args, profiler_key, val)
quantization = kwargs.get("quantization")
if quantization is not None:
if not hasattr(cfg.engine_args, "quantization") or cfg.engine_args.quantization is None:
+14
View File
@@ -114,6 +114,9 @@ class OrchestratorRequestState:
streaming: StreamingInputState = field(default_factory=lambda: StreamingInputState())
# Per-request pipeline timing accumulator (milliseconds)
pipeline_timings: dict[str, float] = field(default_factory=dict)
@dataclass
class StreamingInputState:
@@ -625,6 +628,7 @@ class Orchestrator:
total_token=self._agg_total_tokens[stage_id],
total_gen_time_ms=self._agg_total_gen_time_ms[stage_id],
),
pipeline_timings=dict(req_state.pipeline_timings),
)
def _build_kv_sender_info(self, sender_stage_ids: list[int]) -> dict[int, dict[str, Any]] | None:
@@ -682,6 +686,7 @@ class Orchestrator:
False,
)
_dt_ar2d = (_time.perf_counter() - _t_ar2d) * 1000
req_state.pipeline_timings["ar2diffusion_ms"] = _dt_ar2d
logger.info(
"[Orchestrator] ar2diffusion req=%s wall_time=%.3fms stage=%d->%d",
req_id,
@@ -911,6 +916,15 @@ class Orchestrator:
)
req_state.streaming.enabled = is_streaming
req_state.stage_submit_ts[stage_id] = _time.time()
# Per-request pipeline timings from caller thread
_enqueue_ts = msg.get("enqueue_ts", 0.0)
if _enqueue_ts > 0:
req_state.pipeline_timings["queue_wait_ms"] = (_time.perf_counter() - _enqueue_ts) * 1000.0
_preprocess_ms = msg.get("preprocess_ms", 0.0)
if _preprocess_ms > 0:
req_state.pipeline_timings["preprocess_ms"] = _preprocess_ms
self.request_states[request_id] = req_state
# Stage-0 prompt is already a fully-formed OmniEngineCoreRequest
+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
+42 -1
View File
@@ -41,6 +41,7 @@ class StageRequestStats:
postprocess_time_ms: float = 0.0
diffusion_metrics: dict[str, int] = None
audio_generated_frames: int = 0
pipeline_timings: dict[str, float] | None = None
@property
def rx_mbps(self) -> float:
@@ -101,6 +102,7 @@ STAGE_EXCLUDE = {
"rx_decode_time_ms",
"rx_in_flight_time_ms",
"final_output_type",
"pipeline_timings",
}
TRANSFER_EXCLUDE = {"from_stage", "to_stage", "request_id", "used_shm"}
E2E_EXCLUDE = {"request_id"}
@@ -487,6 +489,15 @@ class OrchestratorAggregator:
"e2e_avg_time_per_request_ms": float(e2e_avg_req),
"e2e_avg_tokens_per_s": float(e2e_avg_tok),
}
# Add average input preprocess time across all requests
preprocess_times = []
for _rid, evts in self.stage_events.items():
for evt in evts:
if evt.pipeline_timings and "preprocess_ms" in evt.pipeline_timings:
preprocess_times.append(evt.pipeline_timings["preprocess_ms"])
break # only once per request
if preprocess_times:
overall_summary["input_preprocess_time_ms"] = sum(preprocess_times) / len(preprocess_times)
# Add stage_wall_time_ms as separate fields for each stage
for idx, wall_time in enumerate(stage_wall_time_ms):
overall_summary[f"e2e_stage_{idx}_wall_time_ms"] = wall_time
@@ -534,11 +545,41 @@ class OrchestratorAggregator:
),
)
# === Stage table (columns = stage_id) ===
# === [OmniTiming] concise per-request summary ===
stage_evts = sorted(
self.stage_events.get(rid, []),
key=lambda e: e.stage_id if e.stage_id is not None else -1,
)
pt = {}
if stage_evts:
pt = stage_evts[-1].pipeline_timings or {}
if pt or e2e_evt:
parts = [f"req={rid}"]
if e2e_evt:
parts.append(f"total={e2e_evt.e2e_total_ms / 1000.0:.2f}s")
if "preprocess_ms" in pt:
parts.append(f"preprocess={pt['preprocess_ms'] / 1000.0:.2f}s")
if e2e_evt:
engine_ms = e2e_evt.e2e_total_ms - pt.get("preprocess_ms", 0.0)
parts.append(f"engine={engine_ms / 1000.0:.2f}s")
stage_parts = []
for evt in stage_evts:
sid = evt.stage_id if evt.stage_id is not None else "?"
t = evt.stage_gen_time_ms / 1000.0
stage_parts.append(f"{sid}:{t:.2f}s")
if stage_parts:
parts.append(f"stages=[{','.join(stage_parts)}]")
transfer_parts = []
for te in self.transfer_events.values():
if te.request_id == rid:
transfer_parts.append(f"{te.from_stage}->{te.to_stage}={te.tx_time_ms:.2f}ms")
if transfer_parts:
parts.append(f"transfers=[{','.join(transfer_parts)}]")
if "ar2diffusion_ms" in pt:
parts.append(f"ar2diffusion={pt['ar2diffusion_ms']:.2f}ms")
logger.info("[OmniTiming] %s", " ".join(parts))
# === Stage table (columns = stage_id) ===
# if any stage has diffusion_metrics, remove postprocess_time_ms field
# because it is already included in diffusion_metrics
local_exclude = STAGE_EXCLUDE.copy()
@@ -330,6 +330,13 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
- Grid dimension calculation for M-RoPE position encoding
"""
def _cached_apply_hf_processor(self, inputs, timing_ctx):
# i2i: prompt text must be modified based on mm data presence,
# and grid computation requires all images together — bypass cache.
if inputs.mm_data_items.get_all_counts().get("image", 0) > 0:
return self._apply_hf_processor(inputs, timing_ctx)
return super()._cached_apply_hf_processor(inputs, timing_ctx)
def _call_hf_processor(
self,
prompt: str,
@@ -678,7 +685,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
try:
mrope_grid_thw = self._build_generation_grids(hf_processor_mm_kwargs)
mm_processed_data["mrope_image_grid_thw"] = mrope_grid_thw
logger.info(
logger.debug(
"_apply_hf_processor_main t2i: mrope_image_grid_thw=%s",
mrope_grid_thw.tolist(),
)
@@ -786,7 +793,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
hf_config = self.info.get_hf_config()
image_token_id = getattr(hf_config, "image_token_id", 167855)
image_token_count = prompt_ids.count(image_token_id)
logger.info(
logger.debug(
"_apply_hf_processor_main i2i(HF): num_images=%s, prompt_len=%s, image_token_count=%s, "
"source_grid_shape=%s, mrope_grid_shape=%s",
num_images,
@@ -2327,7 +2334,7 @@ class GlmImageModel(nn.Module):
# Debug: log prior_token_image_ids_info
shapes = [t.shape for t in upsampled_token_ids]
logger.info(
logger.debug(
f"[GlmImageModel.forward] Built prior_token_image_ids_info: "
f"num_images={len(upsampled_token_ids)}, shapes={shapes}, "
f"image_grid_thw={image_grid_thw.tolist()}"
@@ -2537,7 +2544,7 @@ class GlmImageForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP
# Debug: log prior_token_info
shapes = [t.shape for t in upsampled_token_ids]
logger.info(
logger.debug(
f"[_process_image_input] Built prior_token_info: "
f"num_images={len(upsampled_token_ids)}, shapes={shapes}, "
f"image_grid_thw={image_grid_thw.tolist()}"