refactor: reduce copied vLLM 0.29 compatibility code
Reuse upstream weight mapping and multimodal processing, consolidate Omni processor bridges, and trim unused Hunyuan internals. Route no-media kwargs through the active renderer and preserve GLM generation prompt formatting. Validation: 453 CPU tests passed, 7 skipped; processor imports, Ruff, and diff checks passed. GPU and end-to-end CI not rerun. Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
This commit is contained in:
1 parent
eef8e2bb94
commit
efda9369a8
37 files changed
+448
-1506
No files matched your search
@@ -82,7 +82,6 @@ from vllm.multimodal.inputs import (
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
ImageProcessorItems,
|
||||
MultiModalDataItems,
|
||||
MultiModalDataParser,
|
||||
)
|
||||
@@ -360,282 +359,36 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
return super()._cached_apply_hf_processor(inputs, timing_ctx)
|
||||
|
||||
def apply(self, inputs, timing_ctx):
|
||||
"""Ensure token prompts contain one source-image placeholder each."""
|
||||
"""Add the generation scaffold before upstream expands source images."""
|
||||
num_images = inputs.mm_data_items.get_all_counts().get("image", 0)
|
||||
prompt_ids = list(inputs.prompt)
|
||||
if num_images:
|
||||
image_token_id = getattr(
|
||||
self.info.get_hf_config(),
|
||||
"image_token_id",
|
||||
167855,
|
||||
)
|
||||
prompt_ids = list(inputs.prompt)
|
||||
missing = num_images - prompt_ids.count(image_token_id)
|
||||
if missing > 0:
|
||||
inputs = replace(
|
||||
inputs,
|
||||
prompt=[image_token_id] * missing + prompt_ids,
|
||||
)
|
||||
return super().apply(inputs, timing_ctx)
|
||||
prompt_ids = [image_token_id] * missing + prompt_ids
|
||||
|
||||
def _call_hf_processor(
|
||||
self,
|
||||
prompt: str,
|
||||
mm_data: Mapping[str, object],
|
||||
mm_kwargs: Mapping[str, object],
|
||||
tok_kwargs: Mapping[str, object],
|
||||
) -> BatchFeature:
|
||||
"""
|
||||
Call the HuggingFace processor.
|
||||
|
||||
For text-to-image mode (no images), we need to:
|
||||
1. Build the prompt with target grid dimensions
|
||||
2. Build the image_grid_thw tensor for M-RoPE position encoding
|
||||
|
||||
For image-to-image mode:
|
||||
1. Process source images through the image processor
|
||||
2. Build prompt with image placeholders expanded
|
||||
3. Build image_grid_thw including source and target grids
|
||||
"""
|
||||
processor = self.info.get_hf_processor()
|
||||
|
||||
# Get target dimensions from mm_kwargs or use defaults
|
||||
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:
|
||||
# Build messages format expected by processor
|
||||
messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
||||
|
||||
# Use apply_chat_template which handles target dimensions
|
||||
hf_inputs = processor.apply_chat_template(
|
||||
messages,
|
||||
tokenize=True,
|
||||
target_h=target_h,
|
||||
target_w=target_w,
|
||||
return_dict=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
return hf_inputs
|
||||
else:
|
||||
# Fallback: just tokenize (this won't work properly for generation)
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
prompt_ids = tokenizer.encode(prompt)
|
||||
return BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")
|
||||
|
||||
# Image-to-image mode
|
||||
# NOTE: Use "images" (plural) - this is what vLLM's ImageProcessorItems.get_processor_data() returns
|
||||
images = mm_data.get("images")
|
||||
if not isinstance(images, list):
|
||||
images = [images]
|
||||
|
||||
logger.debug(
|
||||
f"_call_hf_processor i2i: num_images={len(images)}, image_types={[type(img).__name__ for img in images]}"
|
||||
)
|
||||
|
||||
if processor is not None:
|
||||
# Build messages with image objects directly in content
|
||||
# This is how GlmImageProcessor expects images - embedded in the content dict
|
||||
# NOT as a separate images= parameter
|
||||
#
|
||||
# IMPORTANT: Remove <|image|> placeholders from prompt since apply_chat_template
|
||||
# will automatically insert them for each image in content. Having both leads to
|
||||
# index out of bounds when processing image_grid_thw.
|
||||
clean_prompt = prompt.replace("<|image|>", "")
|
||||
content = []
|
||||
for img in images:
|
||||
content.append({"type": "image", "image": img})
|
||||
content.append({"type": "text", "text": clean_prompt})
|
||||
messages = [{"role": "user", "content": content}]
|
||||
|
||||
logger.debug(f"_call_hf_processor: calling apply_chat_template with {len(images)} images in content")
|
||||
|
||||
# Use apply_chat_template - processor will process images when they're in content
|
||||
hf_inputs = processor.apply_chat_template(
|
||||
messages,
|
||||
tokenize=True,
|
||||
target_h=target_h,
|
||||
target_w=target_w,
|
||||
return_dict=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
logger.debug(f"_call_hf_processor: apply_chat_template returned keys: {list(hf_inputs.keys())}")
|
||||
|
||||
# IMPORTANT (i2i): vLLM multimodal encoder must see source-only grids
|
||||
# (matching pixel_values and number of images), but M-RoPE needs full
|
||||
# grids (source + target) to compute correct decode positions.
|
||||
image_grid_thw = hf_inputs.get("image_grid_thw")
|
||||
if image_grid_thw is not None:
|
||||
# Preserve full grids for M-RoPE.
|
||||
hf_inputs["mrope_image_grid_thw"] = image_grid_thw
|
||||
|
||||
# Expose source-only grids for MM.
|
||||
# In most i2i requests, we process one prompt at a time here,
|
||||
# so `len(images)` is the number of source images.
|
||||
num_source_images = len(images)
|
||||
if image_grid_thw.shape[0] != num_source_images:
|
||||
source_grids = image_grid_thw[:num_source_images]
|
||||
hf_inputs["image_grid_thw"] = source_grids
|
||||
logger.debug(
|
||||
"_call_hf_processor: adjusted image_grid_thw for MM from %s to %s (num_source_images=%d)",
|
||||
tuple(image_grid_thw.shape),
|
||||
tuple(source_grids.shape),
|
||||
num_source_images,
|
||||
)
|
||||
|
||||
# Debug: Analyze input_ids for image tokens
|
||||
input_ids = hf_inputs.get("input_ids")
|
||||
if input_ids is not None:
|
||||
if hasattr(input_ids, "tolist"):
|
||||
ids_list = input_ids.tolist()
|
||||
if isinstance(ids_list[0], list):
|
||||
ids_list = ids_list[0] # Unbatch
|
||||
else:
|
||||
ids_list = list(input_ids)
|
||||
|
||||
# Get image token ID from config
|
||||
hf_config = self.info.get_hf_config()
|
||||
image_token_id = getattr(hf_config, "image_token_id", 167855)
|
||||
|
||||
# Count image tokens
|
||||
image_token_count = ids_list.count(image_token_id)
|
||||
logger.debug(
|
||||
f"_call_hf_processor: input_ids length={len(ids_list)}, "
|
||||
f"image_token_id={image_token_id}, "
|
||||
f"image_token_count={image_token_count}"
|
||||
)
|
||||
|
||||
# Log first/last few tokens to understand structure
|
||||
logger.debug(f"_call_hf_processor: first 20 tokens: {ids_list[:20]}")
|
||||
logger.debug(f"_call_hf_processor: last 20 tokens: {ids_list[-20:]}")
|
||||
|
||||
# Find positions of image tokens
|
||||
image_positions = [i for i, t in enumerate(ids_list) if t == image_token_id]
|
||||
if image_positions:
|
||||
logger.debug(f"_call_hf_processor: image token positions (first 10): {image_positions[:10]}")
|
||||
|
||||
return hf_inputs
|
||||
else:
|
||||
# Fallback without processor - this is not ideal but prevents crashes
|
||||
logger.warning("GlmImageProcessor not available, using fallback for i2i")
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
hf_config = self.info.get_hf_config()
|
||||
|
||||
# Get image token
|
||||
image_token_id = getattr(hf_config, "image_token_id", 167855)
|
||||
try:
|
||||
image_token = tokenizer.convert_ids_to_tokens(image_token_id)
|
||||
except Exception:
|
||||
image_token = "<|image|>"
|
||||
|
||||
# Build prompt with image placeholders
|
||||
image_placeholders = image_token * len(images)
|
||||
full_prompt = f"{image_placeholders}{prompt}"
|
||||
prompt_ids = tokenizer.encode(full_prompt)
|
||||
return BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")
|
||||
|
||||
def _apply_hf_processor_mm_only(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
tokenization_kwargs: Mapping[str, object],
|
||||
) -> BatchFeature:
|
||||
"""
|
||||
Apply the HF processor on the multi-modal data only.
|
||||
|
||||
GLM-Image requires special handling because apply_chat_template always
|
||||
adds a target <|image|> placeholder in addition to source image placeholders.
|
||||
This causes an IndexError when the HF processor tries to find grid info
|
||||
for the target placeholder (which doesn't exist for source-only processing).
|
||||
|
||||
Solution: Call the image processor directly to get pixel_values and
|
||||
image_grid_thw, bypassing apply_chat_template's target handling.
|
||||
"""
|
||||
mm_counts = mm_items.get_all_counts()
|
||||
num_images = mm_counts.get("image", 0)
|
||||
|
||||
if num_images == 0:
|
||||
# No images - call parent implementation
|
||||
return super()._apply_hf_processor_mm_only(
|
||||
mm_items=mm_items,
|
||||
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
|
||||
tokenization_kwargs=tokenization_kwargs,
|
||||
)
|
||||
|
||||
# For i2i mode, we need to process images directly with the image processor
|
||||
# to avoid the apply_chat_template target placeholder issue
|
||||
processor = self.info.get_hf_processor()
|
||||
image_processor = processor.image_processor
|
||||
|
||||
# Get images from mm_items
|
||||
images = mm_items.get_items("image", ImageProcessorItems)
|
||||
image_list = [images.get(i) for i in range(images.get_count())]
|
||||
|
||||
logger.debug(f"_apply_hf_processor_mm_only: processing {len(image_list)} images directly")
|
||||
|
||||
# Process images directly with image processor
|
||||
image_inputs = image_processor(
|
||||
images=image_list,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
# Get grid info for source images only (no target)
|
||||
pixel_values = image_inputs.get("pixel_values")
|
||||
image_grid_thw = image_inputs.get("image_grid_thw")
|
||||
if image_grid_thw is not None and image_grid_thw.shape[0] != num_images:
|
||||
# Be defensive: some processors may include extra target grids.
|
||||
image_grid_thw = image_grid_thw[:num_images]
|
||||
image_inputs["image_grid_thw"] = image_grid_thw
|
||||
|
||||
logger.debug(
|
||||
f"_apply_hf_processor_mm_only: pixel_values shape=\
|
||||
{pixel_values.shape if pixel_values is not None else None}, "
|
||||
f"image_grid_thw shape={image_grid_thw.shape if image_grid_thw is not None else None}"
|
||||
)
|
||||
|
||||
# Build input_ids with image token placeholders
|
||||
# The _get_prompt_updates returns PromptReplacement(target=[image_token_id], ...)
|
||||
# which needs to find image tokens in input_ids to replace them.
|
||||
# We need to include one image_token_id per image so the replacement can work.
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
image_token_id = tokenizer.convert_tokens_to_ids("<|image|>")
|
||||
|
||||
# Build input_ids: [image_token] * num_images + tokenized text
|
||||
# This way _apply_prompt_updates can find the image tokens and replace them
|
||||
dummy_text = self.dummy_inputs.get_dummy_text(mm_counts)
|
||||
text_ids = tokenizer.encode(dummy_text, add_special_tokens=False)
|
||||
input_ids = [image_token_id] * num_images + text_ids
|
||||
|
||||
logger.debug(
|
||||
f"_apply_hf_processor_mm_only: built input_ids with {num_images} image tokens + {len(text_ids)} text tokens"
|
||||
# Reuse HF's shape formatter without decoding/re-tokenizing the user's
|
||||
# tokens. Text-to-image needs both target and preview grids; i2i needs
|
||||
# only the target. Grid metadata alone does not supply these AR tokens.
|
||||
target_grid = self._build_generation_grids(inputs.hf_processor_mm_kwargs)[0]
|
||||
suffix, *_ = processor._build_prompt_with_target_shape(
|
||||
"",
|
||||
height=int(target_grid[1]) * 32,
|
||||
width=int(target_grid[2]) * 32,
|
||||
is_text_to_image=num_images == 0,
|
||||
)
|
||||
|
||||
return BatchFeature(
|
||||
dict(
|
||||
input_ids=[input_ids],
|
||||
pixel_values=pixel_values,
|
||||
image_grid_thw=image_grid_thw,
|
||||
),
|
||||
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
|
||||
suffix_ids = tokenizer.encode(suffix, add_special_tokens=False)
|
||||
if prompt_ids[-len(suffix_ids) :] != suffix_ids:
|
||||
prompt_ids.extend(suffix_ids)
|
||||
inputs = replace(inputs, prompt=prompt_ids)
|
||||
return super().apply(inputs, timing_ctx)
|
||||
|
||||
def _build_generation_grids(self, hf_processor_mm_kwargs: Mapping[str, object]) -> torch.Tensor:
|
||||
"""Build generation grids for M-RoPE decode positions.
|
||||
@@ -678,174 +431,6 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
dtype=torch.long,
|
||||
)
|
||||
|
||||
def _apply_hf_processor_main(
|
||||
self,
|
||||
prompt: str | list[int],
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
tokenization_kwargs: Mapping[str, object],
|
||||
*,
|
||||
enable_hf_prompt_update: bool,
|
||||
) -> tuple[list[int], BatchFeature, bool]:
|
||||
"""
|
||||
Override to handle GLM-Image i2i mode correctly.
|
||||
|
||||
Problem: When vLLM processes cached mm items (enable_hf_prompt_update=False),
|
||||
the base implementation:
|
||||
1. Gets prompt_ids from _apply_hf_processor_text_only (no image tokens)
|
||||
2. Gets mm_data from _apply_hf_processor_mm_only
|
||||
3. Returns is_update_applied=False
|
||||
|
||||
This causes _apply_prompt_updates to fail because prompt_ids has no image tokens.
|
||||
|
||||
Solution: For i2i mode, we build prompt_ids that include image placeholders,
|
||||
and return is_update_applied=False so _apply_prompt_updates can expand them.
|
||||
"""
|
||||
mm_counts = mm_items.get_all_counts()
|
||||
num_images = mm_counts.get("image", 0)
|
||||
|
||||
logger.debug(f"_apply_hf_processor_main: mm_counts={mm_counts}, num_images={num_images}")
|
||||
|
||||
if num_images == 0 and isinstance(prompt, str):
|
||||
# t2i mode or normal flow - use parent implementation
|
||||
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,
|
||||
)
|
||||
|
||||
# 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.debug(
|
||||
"_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)
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
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__,
|
||||
)
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
# Preserve full grids for M-RoPE decode (source + target), while
|
||||
# keeping image_grid_thw source-only for MM batching.
|
||||
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):
|
||||
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
|
||||
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:
|
||||
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:
|
||||
prompt_ids = (
|
||||
input_ids[0]
|
||||
if isinstance(input_ids, list) and input_ids and isinstance(input_ids[0], list)
|
||||
else list(input_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
|
||||
|
||||
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.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,
|
||||
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,
|
||||
)
|
||||
|
||||
# HF processor already expanded image placeholders in input_ids.
|
||||
return prompt_ids, mm_processed_data, True
|
||||
|
||||
def _apply_hf_processor_main(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
@@ -891,7 +476,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
Get the multimodal field configuration.
|
||||
|
||||
For GLM-Image i2i mode:
|
||||
- image_grid_thw has been sliced in _call_hf_processor to only include source images
|
||||
- image_grid_thw contains only source grids from _apply_hf_processor_main
|
||||
- pixel_values has shape [total_patches, C, H, W] - only for source images
|
||||
|
||||
For t2i mode:
|
||||
@@ -899,7 +484,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
"""
|
||||
result = {}
|
||||
|
||||
# Get image_grid_thw if present (already sliced in _call_hf_processor)
|
||||
# Get the source-only image_grid_thw if present.
|
||||
image_grid_thw = hf_inputs.get("image_grid_thw")
|
||||
|
||||
if "pixel_values" in hf_inputs and image_grid_thw is not None:
|
||||
@@ -916,7 +501,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
|
||||
result["pixel_values"] = MultiModalFieldConfig.flat_from_sizes("image", image_grid_sizes)
|
||||
|
||||
# Register image_grid_thw - it's been sliced in _call_hf_processor
|
||||
# Register image_grid_thw - it's been sliced in _apply_hf_processor_main
|
||||
# to only include source image grids, so batching will work correctly
|
||||
result["image_grid_thw"] = MultiModalFieldConfig.batched("image")
|
||||
|
||||
@@ -931,37 +516,6 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
|
||||
return result
|
||||
|
||||
def _hf_processor_applies_updates(
|
||||
self,
|
||||
prompt_text: str,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
tokenization_kwargs: Mapping[str, object],
|
||||
) -> bool:
|
||||
"""
|
||||
Return whether the HF processor applies prompt updates.
|
||||
|
||||
For GLM-Image i2i mode, the HF processor's apply_chat_template already
|
||||
expands <|image|> to N tokens (e.g., 4096 for 64x64 grid).
|
||||
|
||||
By returning True, we tell vLLM that HF processor DID apply prompt updates,
|
||||
so vLLM will use _find_mm_placeholders to locate the expanded tokens
|
||||
instead of trying to apply replacements.
|
||||
|
||||
For t2i mode (no images), there are no image placeholders to expand.
|
||||
"""
|
||||
# Check if we have images (i2i mode)
|
||||
num_images = mm_items.get_all_counts().get("image", 0)
|
||||
if num_images > 0:
|
||||
logger.debug(
|
||||
f"_hf_processor_applies_updates: returning True for i2i mode "
|
||||
f"(num_images={num_images}) - HF processor already expanded tokens"
|
||||
)
|
||||
return True
|
||||
|
||||
# For t2i mode (no images), use default behavior
|
||||
return True
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
@@ -971,17 +525,8 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
"""
|
||||
Get prompt updates for image tokens.
|
||||
|
||||
For GLM-Image image-to-image mode, the HF processor's apply_chat_template
|
||||
already expands each <|image|> placeholder to the correct number of
|
||||
image tokens (grid_h * grid_w tokens per source image).
|
||||
|
||||
The HF processor does:
|
||||
1. Replace each <|image|> with num_image_tokens copies of <|placeholder|>
|
||||
2. Replace all <|placeholder|> back to <|image|>
|
||||
|
||||
So the tokenized input already has the expanded tokens. We use
|
||||
target=[image_token_id] to match each occurrence of the image token,
|
||||
similar to how Qwen2VL handles this pattern.
|
||||
Expand each source-image placeholder into grid_h * grid_w image tokens
|
||||
through vLLM's token-based prompt updates.
|
||||
|
||||
We use image_grid_thw from out_mm_kwargs to get the actual processed grid
|
||||
size, following the Qwen2VL pattern. This is critical because the HF processor
|
||||
@@ -992,8 +537,7 @@ class GlmImageMultiModalProcessor(BaseMultiModalProcessor[GlmImageProcessingInfo
|
||||
"""
|
||||
hf_config = self.info.get_hf_config()
|
||||
|
||||
# Get image token ID - this is the token that appears multiple times
|
||||
# in the tokenized input after HF processor expansion
|
||||
# Match the source-image placeholder in the tokenized input.
|
||||
image_token_id = getattr(hf_config, "image_token_id", 167855)
|
||||
|
||||
# Debug: log mm_items info
|
||||
|
||||
Reference in new issue
Block a user