[Bugfix] Fix GLM-Image output dimensions and image edit pipeline (#2320)
Signed-off-by: JaredforReal <w13431838023@gmail.com> Signed-off-by: Jared Wen <w13431838023@gmail.com> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
1 parent
c2859e9cd7
commit
7e28eda929
13 files changed
+1557
-231
No files matched your search
@@ -304,20 +304,9 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# 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)
|
||||
extracted_prompt, reference_images = self._extract_diffusion_prompt_and_images_from_messages(
|
||||
request.messages
|
||||
)
|
||||
if not extracted_prompt:
|
||||
return self.create_error_response("No text prompt found in messages")
|
||||
|
||||
@@ -328,41 +317,33 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
extra_body = getattr(request, "extra_body", None)
|
||||
if not extra_body:
|
||||
extra_body = request.model_extra or {}
|
||||
height = extra_body.get("height")
|
||||
width = extra_body.get("width")
|
||||
|
||||
height, width = self._resolve_height_width_from_extra_body(extra_body)
|
||||
|
||||
num_inference_steps = extra_body.get("num_inference_steps")
|
||||
if num_inference_steps is not None:
|
||||
try:
|
||||
num_inference_steps = int(num_inference_steps)
|
||||
except Exception:
|
||||
num_inference_steps = None
|
||||
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")
|
||||
cfg_text_scale = extra_body.get("cfg_text_scale")
|
||||
cfg_img_scale = extra_body.get("cfg_img_scale")
|
||||
|
||||
engine_prompt_image: dict[str, Any] | None = None
|
||||
is_img2img = False
|
||||
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 = {"img2img": img}
|
||||
is_img2img = True
|
||||
except Exception:
|
||||
engine_prompt_image = None
|
||||
|
||||
# Override the prompts produced by chat-template preprocessing.
|
||||
tprompt: OmniTextPrompt = {"prompt": extracted_prompt}
|
||||
if is_img2img:
|
||||
if engine_prompt_image:
|
||||
tprompt["modalities"] = ["img2img"]
|
||||
else:
|
||||
tprompt["modalities"] = ["image"]
|
||||
@@ -378,6 +359,13 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
tprompt["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
if engine_prompt_image is not None:
|
||||
tprompt["multi_modal_data"] = engine_prompt_image
|
||||
# Provide multi_modal_uuids so that newer vLLM versions
|
||||
# can validate multi_modal_data / multi_modal_uuids
|
||||
# consistency. After the multimodal processor consumes
|
||||
# the image data, the uuids remain as a stable reference.
|
||||
tprompt["multi_modal_uuids"] = {
|
||||
k: [f"{request_id}-{k}-{i}"] for i, k in enumerate(engine_prompt_image)
|
||||
}
|
||||
|
||||
engine_prompts = [tprompt]
|
||||
# Store height/width for applying to diffusion stage sampling params later
|
||||
@@ -544,20 +532,7 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
# containing image tokens.
|
||||
req_modalities = getattr(request, "modalities", [])
|
||||
if req_modalities and ("image" in req_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)
|
||||
extracted_prompt, _ = self._extract_diffusion_prompt_and_images_from_messages(messages)
|
||||
if extracted_prompt:
|
||||
engine_prompt["prompt"] = extracted_prompt
|
||||
|
||||
@@ -717,6 +692,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.
|
||||
|
||||
Args:
|
||||
default_params: Default SamplingParams from stage config YAML.
|
||||
request: The chat completion request containing user-provided values.
|
||||
@@ -726,11 +704,56 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
"""
|
||||
params = default_params.clone()
|
||||
|
||||
# Only apply fields explicitly provided by user, not protocol defaults.
|
||||
# Pydantic v2 uses `model_fields_set`; keep v1 fallback for compatibility.
|
||||
explicit_fields = getattr(request, "model_fields_set", None)
|
||||
if explicit_fields is None:
|
||||
explicit_fields = getattr(request, "__fields_set__", set())
|
||||
|
||||
for field_name in self._OPENAI_SAMPLING_FIELDS:
|
||||
if field_name not in explicit_fields:
|
||||
continue
|
||||
|
||||
value = getattr(request, field_name, None)
|
||||
if (value is not None and not isinstance(value, list)) or (isinstance(value, list) and len(value) > 0):
|
||||
setattr(params, field_name, value)
|
||||
|
||||
# For GLM-Image: compute max_tokens from height/width with mode-aware
|
||||
# budgeting (t2i vs i2i).
|
||||
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,
|
||||
)
|
||||
|
||||
return params
|
||||
|
||||
@staticmethod
|
||||
@@ -2643,6 +2666,48 @@ class OmniOpenAIServingChat(OpenAIServingChat, AudioMixin):
|
||||
prompt = " ".join(prompt_parts).strip()
|
||||
return prompt, images
|
||||
|
||||
def _extract_diffusion_prompt_and_images_from_messages(
|
||||
self,
|
||||
messages: list[Any],
|
||||
) -> tuple[str, list[str]]:
|
||||
"""Normalize mixed message types and extract prompt + reference images once."""
|
||||
return self._extract_diffusion_prompt_and_images(self._messages_to_dicts(messages))
|
||||
|
||||
@staticmethod
|
||||
def _messages_to_dicts(messages: list[Any]) -> list[dict[str, Any]]:
|
||||
"""Normalize request messages to plain dicts."""
|
||||
out: list[dict[str, Any]] = []
|
||||
for msg in messages:
|
||||
if hasattr(msg, "model_dump"):
|
||||
out.append(msg.model_dump())
|
||||
elif isinstance(msg, dict):
|
||||
out.append(msg)
|
||||
else:
|
||||
out.append(
|
||||
{
|
||||
"role": getattr(msg, "role", "user"),
|
||||
"content": getattr(msg, "content", ""),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _resolve_height_width_from_extra_body(extra_body: dict[str, Any]) -> tuple[Any, Any]:
|
||||
"""Extract generation height/width with optional size string fallback."""
|
||||
height = extra_body.get("height")
|
||||
width = extra_body.get("width")
|
||||
|
||||
if "size" in extra_body and (height is None or width is None):
|
||||
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
|
||||
|
||||
return height, width
|
||||
|
||||
def _create_error_response(
|
||||
self,
|
||||
message: str,
|
||||
|
||||
Reference in new issue
Block a user