[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:
Jared WenandHongsheng Liu authored and GitHub committed 2026-04-20 19:24:06 +08:00
1 parent c2859e9cd7
commit 7e28eda929
13 files changed
+1557 -231

No files matched your search

@@ -21,6 +21,7 @@
# limitations under the License.
"""Inference-only GLM-Image model compatible with HuggingFace weights."""
import math
import os
from collections.abc import Iterable, Mapping, Sequence
from typing import Annotated, Literal
@@ -127,6 +128,14 @@ class GlmImageDataParser(MultiModalDataParser):
parsers["img2img"] = self._parse_image_data
return parsers
def parse_mm_data(self, mm_data, **kwargs):
# Normalize "img2img" to "image" so the rest of the pipeline
# (mm_hashes, _merge_mm_kwargs) uses a single modality key.
normalized = {}
for k, v in mm_data.items():
normalized["image" if k == "img2img" else k] = v
return super().parse_mm_data(normalized, **kwargs)
class GlmImageProcessingInfo(BaseProcessingInfo):
"""
@@ -346,6 +355,10 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
target_h = mm_kwargs.get("target_h", 1024) if mm_kwargs else 1024
target_w = mm_kwargs.get("target_w", 1024) if mm_kwargs else 1024
logger.debug(
f"_call_hf_processor: target dimensions for generation: {target_h}x{target_w}, mm_kwargs={mm_kwargs}"
)
if not mm_data or not mm_data.get("images"):
# Text-to-image mode
if processor is not None:
@@ -566,6 +579,58 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
tensor_type="pt",
)
def _apply_hf_processor_text_only(
self, prompt_text: str, hf_processor_mm_kwargs: Mapping[str, object], tokenization_kwargs: Mapping[str, object]
) -> list[int]:
prompt_ids, _, _ = super()._apply_hf_processor_text_mm(
prompt_text=prompt_text,
mm_items=MultiModalDataItems({}),
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
return prompt_ids
def _build_generation_grids(self, hf_processor_mm_kwargs: Mapping[str, object]) -> torch.Tensor:
"""Build generation grids for M-RoPE decode positions.
For GLM-Image generation, decode order is:
1) small preview grid
2) large target grid
3) EOS
We store grids as [large, small] to match HF processor behavior, and
decode logic consumes them in reverse order.
"""
target_h = (
hf_processor_mm_kwargs.get("target_h") if isinstance(hf_processor_mm_kwargs.get("target_h"), int) else None
)
target_w = (
hf_processor_mm_kwargs.get("target_w") if isinstance(hf_processor_mm_kwargs.get("target_w"), int) else None
)
if target_h is None or target_w is None:
target_h = (
hf_processor_mm_kwargs.get("height") if isinstance(hf_processor_mm_kwargs.get("height"), int) else 1024
)
target_w = (
hf_processor_mm_kwargs.get("width") if isinstance(hf_processor_mm_kwargs.get("width"), int) else 1024
)
factor = 32
target_h = (target_h // factor) * factor
target_w = (target_w // factor) * factor
token_h = target_h // factor
token_w = target_w // factor
ratio = token_h / token_w if token_w > 0 else 1.0
small_token_h = max(1, int(math.sqrt(ratio) * (factor // 2)))
small_token_w = max(1, int(math.sqrt(1 / ratio) * (factor // 2)))
return torch.tensor(
[[1, token_h, token_w], [1, small_token_h, small_token_w]],
dtype=torch.long,
)
def _apply_hf_processor_main(
self,
prompt: str | list[int],
@@ -594,126 +659,145 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
logger.debug(f"_apply_hf_processor_main: mm_counts={mm_counts}, num_images={num_images}")
if num_images == 0 or enable_hf_prompt_update:
if num_images == 0 and isinstance(prompt, str):
# t2i mode or normal flow - use parent implementation
return super()._apply_hf_processor_main(
prompt=prompt,
prompt_ids = self._apply_hf_processor_text_only(
prompt_text=prompt,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
mm_processed_data = self._apply_hf_processor_mm_only(
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
enable_hf_prompt_update=enable_hf_prompt_update,
)
# i2i mode with enable_hf_prompt_update=False (cache miss scenario)
# We need to build prompt_ids with image placeholders
logger.debug(f"_apply_hf_processor_main: i2i mode with enable_hf_prompt_update=False, num_images={num_images}")
# t2i has no source images, so mm features cannot provide image_grid_thw.
# Provide explicit generation grids for M-RoPE to avoid fallback token parsing
# (which can degrade high-resolution spatial positions, e.g. 1920x1920).
try:
mrope_grid_thw = self._build_generation_grids(hf_processor_mm_kwargs)
mm_processed_data["mrope_image_grid_thw"] = mrope_grid_thw
logger.info(
"_apply_hf_processor_main t2i: mrope_image_grid_thw=%s",
mrope_grid_thw.tolist(),
)
except Exception as e:
logger.warning("_apply_hf_processor_main t2i: failed to set mrope_image_grid_thw: %s", e)
# Get mm data from our overridden _apply_hf_processor_mm_only
mm_processed_data = self._apply_hf_processor_mm_only(
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
return prompt_ids, mm_processed_data, False
# i2i mode: use unified HF processor path only.
# This avoids drift between duplicated manual/HF i2i implementations.
logger.debug(
"_apply_hf_processor_main: i2i mode (enable_hf_prompt_update=%s), num_images=%s",
enable_hf_prompt_update,
num_images,
)
# In this path we do NOT call HF apply_chat_template, so we must still
# provide full grids (source + target) for M-RoPE to compute decode positions.
# Keep `image_grid_thw` source-only for MM batching/validation.
try:
source_grid_thw = mm_processed_data.get("image_grid_thw")
if source_grid_thw is not None and isinstance(source_grid_thw, torch.Tensor):
# Compute target grid following HF GlmImageProcessor: factor=32.
# Prefer explicit target_h/target_w if present, otherwise fall back.
target_h = (
hf_processor_mm_kwargs.get("target_h")
if isinstance(hf_processor_mm_kwargs.get("target_h"), int)
else None
)
target_w = (
hf_processor_mm_kwargs.get("target_w")
if isinstance(hf_processor_mm_kwargs.get("target_w"), int)
else None
)
if target_h is None or target_w is None:
# Some callers pass generation size as height/width.
target_h = (
hf_processor_mm_kwargs.get("height")
if isinstance(hf_processor_mm_kwargs.get("height"), int)
else 1024
)
target_w = (
hf_processor_mm_kwargs.get("width")
if isinstance(hf_processor_mm_kwargs.get("width"), int)
else 1024
)
if not isinstance(prompt, str):
# Online OpenAI chat preprocessing can arrive here with tokenized
# prompts (list[int]) before serving_chat replaces engine prompt
# with the clean text prompt. Do not fail the whole request.
logger.warning(
"_apply_hf_processor_main i2i: got tokenized prompt type=%s; "
"using compatibility path for preprocessing",
type(prompt).__name__,
)
factor = 32
target_h = (target_h // factor) * factor
target_w = (target_w // factor) * factor
token_h = target_h // factor
token_w = target_w // factor
target_grid = torch.tensor([[1, token_h, token_w]], dtype=source_grid_thw.dtype)
prompt_ids = list(prompt)
mm_processed_data = self._apply_hf_processor_mm_only(
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
)
mm_processed_data["mrope_image_grid_thw"] = torch.cat([source_grid_thw, target_grid], dim=0)
except Exception:
# Best-effort only; M-RoPE has additional fallbacks.
pass
# Build prompt_ids with image placeholders
# _apply_prompt_updates will replace each [image_token_id] with expanded tokens
tokenizer = self.info.get_tokenizer()
image_token_id = tokenizer.convert_tokens_to_ids("<|image|>")
if isinstance(prompt, str):
# Match HF GlmImageProcessor behavior: append target grid tokens + BOS.
# This helps M-RoPE/grid parsing and keeps i2i vs t2i behavior aligned.
# Preserve full grids for M-RoPE decode (source + target), while
# keeping image_grid_thw source-only for MM batching.
try:
grid_bos = getattr(tokenizer, "grid_bos_token", "")
grid_eos = getattr(tokenizer, "grid_eos_token", "")
bos = getattr(tokenizer, "bos_token", "")
# Use the same target sizes we used for mrope grids when available.
target_h = (
hf_processor_mm_kwargs.get("target_h")
if isinstance(hf_processor_mm_kwargs.get("target_h"), int)
else None
)
target_w = (
hf_processor_mm_kwargs.get("target_w")
if isinstance(hf_processor_mm_kwargs.get("target_w"), int)
else None
)
if target_h is None or target_w is None:
source_grid_thw = mm_processed_data.get("image_grid_thw")
if source_grid_thw is not None and isinstance(source_grid_thw, torch.Tensor):
target_h = (
hf_processor_mm_kwargs.get("height")
if isinstance(hf_processor_mm_kwargs.get("height"), int)
else 1024
hf_processor_mm_kwargs.get("target_h")
if isinstance(hf_processor_mm_kwargs.get("target_h"), int)
else None
)
target_w = (
hf_processor_mm_kwargs.get("width")
if isinstance(hf_processor_mm_kwargs.get("width"), int)
else 1024
hf_processor_mm_kwargs.get("target_w")
if isinstance(hf_processor_mm_kwargs.get("target_w"), int)
else None
)
if target_h is None or target_w is None:
target_h = (
hf_processor_mm_kwargs.get("height")
if isinstance(hf_processor_mm_kwargs.get("height"), int)
else 1024
)
target_w = (
hf_processor_mm_kwargs.get("width")
if isinstance(hf_processor_mm_kwargs.get("width"), int)
else 1024
)
factor = 32
target_h = (target_h // factor) * factor
target_w = (target_w // factor) * factor
token_h = target_h // factor
token_w = target_w // factor
expanded_prompt = f"{prompt}{grid_bos}{token_h} {token_w}{grid_eos}{bos}"
text_ids = tokenizer.encode(expanded_prompt, add_special_tokens=False)
factor = 32
token_h = max(1, target_h // factor)
token_w = max(1, target_w // factor)
target_grid = torch.tensor([[1, token_h, token_w]], dtype=source_grid_thw.dtype)
mm_processed_data["mrope_image_grid_thw"] = torch.cat([source_grid_thw, target_grid], dim=0)
except Exception:
text_ids = tokenizer.encode(prompt, add_special_tokens=False)
pass
# Prompt updates will expand image placeholders in this compatibility path.
return prompt_ids, mm_processed_data, False
images = mm_items.get_items("image", ImageProcessorItems)
image_list = [images.get(i) for i in range(images.get_count())]
if not image_list:
raise ValueError("GLM-Image i2i requires at least one source image in mm_items")
hf_inputs = self._call_hf_processor(
prompt=prompt,
mm_data={"images": image_list},
mm_kwargs=hf_processor_mm_kwargs,
tok_kwargs=tokenization_kwargs,
)
input_ids = hf_inputs.get("input_ids")
if input_ids is None:
raise ValueError("HF i2i processor returned no input_ids")
if isinstance(input_ids, torch.Tensor):
prompt_ids = input_ids[0].tolist() if input_ids.dim() > 1 else input_ids.tolist()
else:
text_ids = list(prompt)
prompt_ids = (
input_ids[0]
if isinstance(input_ids, list) and input_ids and isinstance(input_ids[0], list)
else list(input_ids)
)
# Prepend image placeholders - one per image
prompt_ids = [image_token_id] * num_images + text_ids
mm_processed_data = BatchFeature(dict(), tensor_type="pt")
for key in ("pixel_values", "image_grid_thw", "mrope_image_grid_thw"):
value = hf_inputs.get(key)
if value is not None:
mm_processed_data[key] = value
logger.debug(f"_apply_hf_processor_main: built prompt_ids with {num_images} image placeholders")
image_grid_thw = mm_processed_data.get("image_grid_thw")
mrope_grid_thw = mm_processed_data.get("mrope_image_grid_thw")
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(
"_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,
len(prompt_ids),
image_token_count,
tuple(image_grid_thw.shape) if image_grid_thw is not None else None,
tuple(mrope_grid_thw.shape) if mrope_grid_thw is not None else None,
)
# Return is_update_applied=False so _apply_prompt_updates will expand the placeholders
return prompt_ids, mm_processed_data, False
# HF processor already expanded image placeholders in input_ids.
return prompt_ids, mm_processed_data, True
def _get_mm_fields_config(
self,
@@ -2667,9 +2751,23 @@ class GlmImageForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP
# Input format: "text<sop>H W<eop><sop>h w<eop><bos>" where <bos>=image_start_token_id=16384
# For 1024x1024: H=32, W=32 (large), h=16, w=16 (small preview)
if not image_grid_thw:
# Preferred path for t2i: use explicit target size propagated from
# serving/request sampling params. This avoids fragile grid parsing
# from token IDs and matches HF processor grid construction.
target_h = kwargs.get("target_h")
target_w = kwargs.get("target_w")
if isinstance(target_h, int) and isinstance(target_w, int) and target_h > 0 and target_w > 0:
factor = 32
token_h = target_h // factor
token_w = target_w // factor
ratio = token_h / token_w if token_w > 0 else 1.0
small_h = max(1, int(math.sqrt(ratio) * (factor // 2)))
small_w = max(1, int(math.sqrt(1 / ratio) * (factor // 2)))
image_grid_thw = [[1, token_h, token_w], [1, small_h, small_w]]
# Try to parse from kwargs (passed from processor)
hf_config_arg = kwargs.get("hf_config")
if hf_config_arg is not None and hasattr(hf_config_arg, "image_grid_thw"):
if (not image_grid_thw) and hf_config_arg is not None and hasattr(hf_config_arg, "image_grid_thw"):
image_grid_thw = hf_config_arg.image_grid_thw
# If still empty, try to infer from input tokens
@@ -2723,19 +2821,29 @@ class GlmImageForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP
prompt_ends_with_start = len(input_tokens) > 0 and input_tokens[-1] == image_start_token_id
if prompt_ends_with_start and len(image_grid_thw) == num_source_images and num_source_images > 0:
# i2i mode: source grids exist but no target grids
# Parse target grids from prompt tokens or use defaults
parsed_grids = self._parse_grid_from_tokens(input_tokens, hf_config)
if parsed_grids:
# parsed_grids contains all grids mentioned in prompt
# For i2i, add only the generation target grids
if len(parsed_grids) > num_source_images:
image_grid_thw = list(image_grid_thw) + parsed_grids[num_source_images:]
else:
# Fallback: add default 1024x1024 generation grids (1 target for i2i)
image_grid_thw = list(image_grid_thw) + [[1, 32, 32]]
# Prefer explicit target size propagated from request sampling params.
# This avoids fragile grid parsing from token IDs for non-1024 i2i.
target_h = kwargs.get("target_h")
target_w = kwargs.get("target_w")
if isinstance(target_h, int) and isinstance(target_w, int) and target_h > 0 and target_w > 0:
factor = 32
token_h = target_h // factor
token_w = target_w // factor
image_grid_thw = list(image_grid_thw) + [[1, token_h, token_w]]
else:
# Fallback to default 1024x1024 grids for generation
image_grid_thw = list(image_grid_thw) + [[1, 32, 32]]
# Parse target grids from prompt tokens or use defaults
parsed_grids = self._parse_grid_from_tokens(input_tokens, hf_config)
if parsed_grids:
# parsed_grids contains all grids mentioned in prompt
# For i2i, add only the generation target grids
if len(parsed_grids) > num_source_images:
image_grid_thw = list(image_grid_thw) + parsed_grids[num_source_images:]
else:
# Fallback: add default 1024x1024 generation grid (1 target for i2i)
image_grid_thw = list(image_grid_thw) + [[1, 32, 32]]
else:
# Fallback to default 1024x1024 grid for generation
image_grid_thw = list(image_grid_thw) + [[1, 32, 32]]
llm_pos_ids_list: list[torch.Tensor] = []
@@ -33,7 +33,6 @@ stage_args:
temperature: 0.9 # From model's generation_config.json
top_p: 0.75 # From model's generation_config.json
top_k: 16512 # vision_vocab_size from generation_config.json
max_tokens: 1281 # For 1024x1024: small(16x16=256) + large(32x32=1024) + EOS(1)
stop_token_ids: [16385] # eos_token_id from generation_config.json
seed: 42
detokenize: false
@@ -35,7 +35,6 @@ stage_args:
temperature: 0.9 # From model's generation_config.json
top_p: 0.75 # From model's generation_config.json
top_k: 16512 # vision_vocab_size from generation_config.json
max_tokens: 1281 # For 1024x1024: small(16x16=256) + large(32x32=1024) + EOS(1)
stop_token_ids: [16385] # eos_token_id from generation_config.json
seed: 42
detokenize: false
@@ -2,6 +2,8 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Stage input processor for GLM-Image: AR → Diffusion transition."""
import math
import time
from typing import Any
import torch
@@ -13,6 +15,86 @@ from vllm_omni.inputs.data import OmniTokensPrompt
logger = init_logger(__name__)
def _has_source_image(mm_data: Any) -> bool:
"""Return whether prompt multi_modal_data contains a source image.
Normalizes legacy/new keys used across omni pipelines:
- `image`: single PIL image or list
- `img2img`: legacy single-image key
- `images`: list or single image
"""
if not isinstance(mm_data, dict):
return False
if mm_data.get("image") is not None:
return True
if mm_data.get("img2img") is not None:
return True
images = mm_data.get("images")
return bool(images)
def _first_source_image(mm_data: Any) -> Any:
"""Get first source image from normalized multimodal keys."""
if not isinstance(mm_data, dict):
return None
image = mm_data.get("image")
if image is not None:
if isinstance(image, list):
return image[0] if image else None
return image
image = mm_data.get("img2img")
if image is not None:
if isinstance(image, list):
return image[0] if image else None
return image
images = mm_data.get("images")
if isinstance(images, list):
return images[0] if images else None
return images
def compute_max_tokens(height: int, width: int, factor: int = 32, is_i2i: bool = False) -> int:
"""
Compute max_new_tokens for GLM-Image AR generation.
GLM-Image generation differs by mode:
- text-to-image (t2i): small preview + large target + EOS
- image-to-image (i2i): large target + EOS
Args:
height: Target image height in pixels
width: Target image width in pixels
factor: Downsampling factor (32 for GLM-Image AR output)
is_i2i: Whether the request is image-to-image mode
Returns:
Total number of tokens to generate for the specified mode
"""
# Large image tokens (target resolution)
token_h = height // factor
token_w = width // factor
large_tokens = token_h * token_w
# Small preview tokens (half resolution in each dimension)
import math
ratio = token_h / token_w if token_w > 0 else 1.0
small_token_h = max(1, int(math.sqrt(ratio) * (factor // 2)))
small_token_w = max(1, int(math.sqrt(1 / ratio) * (factor // 2)))
small_tokens = small_token_h * small_token_w
# Mode-dependent totals:
# - t2i: small + large + EOS
# - i2i: large + EOS
if is_i2i:
return large_tokens + 1
return small_tokens + large_tokens + 1
def _upsample_token_ids(token_ids: torch.Tensor, token_h: int, token_w: int) -> torch.Tensor:
"""Upsample token IDs by 2x using nearest neighbor interpolation.
@@ -56,39 +138,49 @@ def _parse_generated_tokens(
large_image_tokens = token_h * token_w
# Calculate small preview image dimensions (used in text-to-image)
small_token_h = token_h // 2
small_token_w = token_w // 2
ratio = token_h / token_w if token_w > 0 else 1.0
small_token_h = max(1, int(math.sqrt(ratio) * (factor // 2)))
small_token_w = max(1, int(math.sqrt(1 / ratio) * (factor // 2)))
small_image_tokens = small_token_h * small_token_w
token_tensor = torch.tensor(token_ids, dtype=torch.long)
# Remove EOS token (16385) from the end if present
eos_token_id = 16385
if len(token_ids) > 0 and token_ids[-1] == eos_token_id:
has_terminal_eos = len(token_ids) > 0 and token_ids[-1] == eos_token_id
if has_terminal_eos:
token_tensor = token_tensor[:-1]
actual_tokens = len(token_tensor)
logger.debug(
f"[_parse_generated_tokens] height={height}, width={width}, "
f"token_h={token_h}, token_w={token_w}, "
f"large_image_tokens={large_image_tokens}, small_image_tokens={small_image_tokens}, "
f"actual_tokens={actual_tokens}"
)
if is_i2i:
# Image-to-image mode: check if AR generated small+large tokens (like t2i) or just large tokens
# Some AR models output small+large even in i2i mode
if actual_tokens >= small_image_tokens + large_image_tokens:
# AR generated full t2i-style output, extract large tokens after small
large_start = small_image_tokens
large_end = large_start + large_image_tokens
prior_token_ids_d32 = token_tensor[large_start:large_end]
actual_h, actual_w = token_h, token_w
else:
# AR generated only large tokens (pure i2i output)
logger.warning(
"[_parse_generated_tokens] i2i detected t2i-style token layout; "
"using small-offset extraction: large_start=%s large_end=%s",
large_start,
large_end,
)
elif actual_tokens >= large_image_tokens:
prior_token_ids_d32 = token_tensor[:large_image_tokens]
actual_h, actual_w = token_h, token_w
logger.info(
"[_parse_generated_tokens] i2i using offset-0 extraction: large_tokens=%s",
large_image_tokens,
)
else:
logger.warning(
"[_parse_generated_tokens] i2i token parse failed: actual_tokens=%s < expected_large_tokens=%s",
actual_tokens,
large_image_tokens,
)
raise ValueError(
f"i2i token parse failed: actual_tokens={actual_tokens} < expected_large_tokens={large_image_tokens}"
)
elif actual_tokens >= small_image_tokens + large_image_tokens:
# Text-to-image: extract large image tokens after small image tokens
large_start = small_image_tokens
@@ -96,43 +188,22 @@ def _parse_generated_tokens(
prior_token_ids_d32 = token_tensor[large_start:large_end]
actual_h, actual_w = token_h, token_w
elif actual_tokens >= large_image_tokens:
# Image-to-image: large image tokens are at the beginning
prior_token_ids_d32 = token_tensor[:large_image_tokens]
actual_h, actual_w = token_h, token_w
logger.warning(
"[_parse_generated_tokens] t2i token parse failed: got only large tokens without small preview "
"(actual_tokens=%s, expected_small_plus_large=%s)",
actual_tokens,
small_image_tokens + large_image_tokens,
)
raise ValueError("t2i token parse failed: missing small-preview tokens; refusing low-quality fallback")
else:
# Insufficient tokens - try to infer the actual grid size
import math
for scale in [1, 2, 4]:
test_h = token_h // scale
test_w = token_w // scale
test_small_h = test_h // 2
test_small_w = test_w // 2
test_large = test_h * test_w
test_small = test_small_h * test_small_w
if actual_tokens >= test_small + test_large:
prior_token_ids_d32 = token_tensor[test_small : test_small + test_large]
actual_h, actual_w = test_h, test_w
height = test_h * factor
width = test_w * factor
logger.warning(f"Adjusted grid to {test_h}x{test_w}, output will be {height}x{width}")
break
elif actual_tokens >= test_large:
prior_token_ids_d32 = token_tensor[:test_large]
actual_h, actual_w = test_h, test_w
height = test_h * factor
width = test_w * factor
logger.warning(f"Adjusted grid to {test_h}x{test_w}, output will be {height}x{width}")
break
else:
sqrt_tokens = int(math.sqrt(actual_tokens))
actual_h = actual_w = sqrt_tokens
usable_tokens = sqrt_tokens * sqrt_tokens
prior_token_ids_d32 = token_tensor[:usable_tokens]
height = sqrt_tokens * factor
width = sqrt_tokens * factor
logger.error(f"Grid pattern mismatch. Using {sqrt_tokens}x{sqrt_tokens}, output: {height}x{width}")
logger.warning(
"[_parse_generated_tokens] token parse failed: insufficient tokens "
"(actual_tokens=%s, expected=%s, mode=%s)",
actual_tokens,
large_image_tokens if is_i2i else (small_image_tokens + large_image_tokens),
"i2i" if is_i2i else "t2i",
)
raise ValueError(f"token parse failed: actual_tokens={actual_tokens}, mode={'i2i' if is_i2i else 't2i'}")
# Upsample from 32x to 16x
prior_token_ids = _upsample_token_ids(prior_token_ids_d32, actual_h, actual_w)
@@ -147,6 +218,8 @@ def ar2diffusion(
requires_multimodal_data: bool = False,
) -> list[dict[str, Any]]:
"""Process AR stage outputs to create Diffusion stage inputs."""
_t_total = time.perf_counter()
if not engine_input_source:
raise ValueError("engine_input_source cannot be empty")
@@ -165,6 +238,7 @@ def ar2diffusion(
prompt = [prompt] if prompt is not None else [{}]
for i, ar_output in enumerate(ar_outputs):
_t_req = time.perf_counter()
output = ar_output.outputs[0]
generated_token_ids = output.token_ids
@@ -179,23 +253,76 @@ def ar2diffusion(
else:
original_prompt = {}
height = original_prompt.get("height", 1024)
width = original_prompt.get("width", 1024)
mm_processor_kwargs = original_prompt.get("mm_processor_kwargs")
def _coerce_dim(v: Any, default: int) -> int:
try:
iv = int(v)
return iv if iv > 0 else default
except (TypeError, ValueError):
return default
# Prefer GLM-Image target size from mm_processor_kwargs (set by serving layer),
# then fall back to top-level fields for backward compatibility.
height = _coerce_dim(
mm_processor_kwargs.get("target_h") if isinstance(mm_processor_kwargs, dict) else None,
_coerce_dim(original_prompt.get("height"), 1024),
)
width = _coerce_dim(
mm_processor_kwargs.get("target_w") if isinstance(mm_processor_kwargs, dict) else None,
_coerce_dim(original_prompt.get("width"), 1024),
)
text_prompt = original_prompt.get("prompt", "")
# Detect i2i mode first by checking if multimodal_output contains prior_token_image_ids
# Detect i2i mode.
# Prefer normalized prompt multi_modal_data source-image presence, with
# multimodal output as secondary signal.
_t_mode = time.perf_counter()
is_i2i = False
prompt_modalities = original_prompt.get("modalities")
if isinstance(prompt_modalities, list) and "img2img" in prompt_modalities:
is_i2i = True
prompt_mm_data = original_prompt.get("multi_modal_data")
if _has_source_image(prompt_mm_data):
is_i2i = True
if hasattr(ar_output, "multimodal_output") and ar_output.multimodal_output:
mm_output = ar_output.multimodal_output
if isinstance(mm_output, dict) and mm_output.get("prior_token_image_ids") is not None:
is_i2i = True
if isinstance(mm_output, dict):
if mm_output.get("prior_token_image_ids") is not None:
is_i2i = True
_dt_mode = (time.perf_counter() - _t_mode) * 1000
# Parse and upsample prior tokens
prior_token_ids, pixel_h, pixel_w = _parse_generated_tokens(generated_token_ids, height, width, is_i2i=is_i2i)
_t_parse = time.perf_counter()
try:
prior_token_ids, pixel_h, pixel_w = _parse_generated_tokens(
generated_token_ids,
height,
width,
is_i2i=is_i2i,
)
except ValueError as e:
logger.warning(
"[ar2diffusion] Request %s: skip due to token parse failure: %s "
"(target=%sx%s, mode=%s, raw_tokens=%s, tail=%s)",
i,
e,
height,
width,
"i2i" if is_i2i else "t2i",
len(generated_token_ids),
generated_token_ids[-8:] if len(generated_token_ids) >= 8 else generated_token_ids,
)
continue
_dt_parse = (time.perf_counter() - _t_parse) * 1000
# Get prior_token_image_ids from AR model output (for i2i mode)
# This contains VQ-VAE tokens from input image, used for KV cache conditioning
# NOTE: multimodal_output is attached to ar_output (RequestOutput), NOT output (CompletionOutput)
_t_prior_img = time.perf_counter()
prior_token_image_ids = None
# Check ar_output (RequestOutput) for multimodal_output - this is the correct location
@@ -234,6 +361,7 @@ def ar2diffusion(
prior_token_image_ids = [raw_prior_image_ids]
elif isinstance(raw_prior_image_ids, list):
prior_token_image_ids = raw_prior_image_ids
_dt_prior_img = (time.perf_counter() - _t_prior_img) * 1000
diffusion_input = {
"prompt": text_prompt,
@@ -248,18 +376,38 @@ def ar2diffusion(
if requires_multimodal_data:
mm_data = original_prompt.get("multi_modal_data")
if mm_data:
pil_image = mm_data.get("image")
if pil_image is None:
# Try "images" (plural) as fallback
images = mm_data.get("images")
if images:
pil_image = images[0] if isinstance(images, list) else images
pil_image = _first_source_image(mm_data)
diffusion_input["pil_image"] = pil_image
for key in ["seed", "num_inference_steps", "guidance_scale", "negative_prompt"]:
if key in original_prompt:
diffusion_input[key] = original_prompt[key]
_dt_req = (time.perf_counter() - _t_req) * 1000
logger.info(
"[ar2diffusion] req=%d mode=%s target=%dx%d "
"raw_tokens=%d prior_tokens=%d prior_image_ids=%s "
"timing: mode_detect=%.3fms parse+upsample=%.3fms "
"prior_image_ids_extract=%.3fms req_total=%.3fms",
i,
"i2i" if is_i2i else "t2i",
pixel_h,
pixel_w,
len(generated_token_ids),
len(prior_token_ids),
"yes" if prior_token_image_ids is not None else "no",
_dt_mode,
_dt_parse,
_dt_prior_img,
_dt_req,
)
diffusion_inputs.append(diffusion_input)
_dt_total = (time.perf_counter() - _t_total) * 1000
logger.info(
"[ar2diffusion] batch done: %d reqs, total=%.3fms",
len(diffusion_inputs),
_dt_total,
)
return diffusion_inputs