[Model] Add Ming-flash-omni-2.0 Image Generation (Diffusion) Stage (#2875)

Signed-off-by: ZhengWG <zwg0606@gmail.com>
Signed-off-by: Zheng Wengang <zwg0606@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Yuanheng Zhao <54058983+yuanheng-zhao@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-05-27 23:21:20 +08:00
1 parent 36dc32ff81
commit a698269e47
25 files changed
+2614 -42

No files matched your search

@@ -126,15 +126,21 @@ class MingFlashOmniForConditionalGeneration(
self.make_empty_intermediate_tensors = self.thinker.make_empty_intermediate_tensors
elif self.model_stage == "imagegen":
# TODO: Implement image generator stage
# Image generation is a separate diffusion stage; it does not run
# through this AR wrapper. See
# ``vllm_omni/diffusion/models/ming_flash_omni/pipeline_ming_imagegen.py``
# and ``model_arch: MingImagePipeline`` in the stage YAML.
raise NotImplementedError(
"Image generation stage is not yet implemented. Please use model_stage='thinker' for now."
"Image generation stage is not implemented in this AR wrapper. "
"Use stage_type: diffusion with model_arch: MingImagePipeline "
"for the imagegen stage (see stage_configs/ming_flash_omni.yaml)."
)
else:
raise ValueError(
f"Invalid model_stage: {self.model_stage!r}. Must be one of: 'thinker', 'imagegen'. "
f"For the talker stage, use MingFlashOmniTalkerForConditionalGeneration directly."
f"For the talker stage, use MingFlashOmniTalkerForConditionalGeneration directly. "
f"For image generation use stage_type: diffusion with model_arch: MingImagePipeline."
)
def forward(
@@ -177,9 +183,43 @@ class MingFlashOmniForConditionalGeneration(
raise NotImplementedError("get_mrope_input_positions not available on current stage")
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stripped = ((name.removeprefix("thinker."), value) for name, value in weights)
thinker_loaded = self.thinker.load_weights(stripped)
return add_prefix_to_loaded_weights(thinker_loaded, "thinker")
loaded_weights: set[str] = set()
thinker_weights: list[tuple[str, torch.Tensor]] = []
for name, value in weights:
if name.startswith("thinker."):
thinker_weights.append((name, value))
elif name.startswith("imagegen."):
# Imagegen weights are loaded by MingImagePipeline (diffusion
# stage) from its own checkpoint subfolders; silently drop
# them here so the AR wrapper does not try to load them.
continue
elif name.startswith("talker."):
# Talker weights are loaded by
# MingFlashOmniTalkerForConditionalGeneration directly; drop.
continue
else:
# Weights without prefix go to thinker by default
thinker_weights.append((name, value))
if self.model_stage == "thinker" and thinker_weights:
stripped = ((name.removeprefix("thinker."), value) for name, value in thinker_weights)
thinker_loaded = self.thinker.load_weights(stripped)
thinker_loaded = add_prefix_to_loaded_weights(thinker_loaded, "thinker")
loaded_weights.update(thinker_loaded)
# ``query_tokens_dict.*`` parameters are pre-loaded inside
# ``MingFlashOmniThinker.__init__`` from
# ``<model>/mlp/model.safetensors`` (not the main shard index),
# so vllm's default loader does not see them via the standard
# ``load_weights`` path. Report them as loaded here to satisfy the
# post-load completeness check.
query_tokens_module = getattr(self.thinker, "query_tokens_dict", None)
if query_tokens_module is not None:
for scale_name, _param in query_tokens_module.items():
loaded_weights.add(f"thinker.query_tokens_dict.{scale_name}")
return loaded_weights
def get_mm_mapping(self) -> MultiModelKeys:
return MultiModelKeys.from_string_field(
@@ -6,6 +6,7 @@
"""Ming-flash-omni-2.0 Thinker stage implementation (multimodal understanding)."""
import os
from collections.abc import Iterable, Iterator, Mapping, Sequence
from typing import Annotated, Any
@@ -113,7 +114,9 @@ class MingFlashOmniThinkerProcessingInfo(Qwen2VLProcessingInfo):
return 1
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
return {"image": None, "video": None, "audio": None}
# ``img2img`` is the serving-layer alias for a reference image in the
# image-gen path; treated as a regular image by ``_MingMultiModalDataParser``.
return {"image": None, "video": None, "audio": None, "img2img": 1}
def get_mm_max_tokens_per_item(
self,
@@ -137,7 +140,14 @@ class MingFlashOmniThinkerProcessingInfo(Qwen2VLProcessingInfo):
return mm_max_tokens
def get_feature_extractor(self, **kwargs: object) -> MingWhisperFeatureExtractor:
def get_feature_extractor(self, **kwargs: object):
"""Return the audio feature extractor from the processor.
The processor may be loaded via trust_remote_code paths that return
a stock transformers ``WhisperFeatureExtractor`` rather than
vllm-omni's subclass ``MingWhisperFeatureExtractor``. We accept both
as long as the caller-needed attributes (``sampling_rate``) exist.
"""
hf_processor = self.get_hf_processor(**kwargs)
feature_extractor = hf_processor.audio_processor
assert isinstance(feature_extractor, MingWhisperFeatureExtractor)
@@ -145,13 +155,56 @@ class MingFlashOmniThinkerProcessingInfo(Qwen2VLProcessingInfo):
def get_data_parser(self):
feature_extractor = self.get_feature_extractor()
return MultiModalDataParser(
return _MingMultiModalDataParser(
target_sr=feature_extractor.sampling_rate,
target_channels=self.get_target_channels(),
expected_hidden_size=self._get_expected_hidden_size(),
)
class _MingMultiModalDataParser(MultiModalDataParser):
"""Rewrite ``img2img`` → ``image`` in-place so the thinker embeds the ref.
Matches Ming's upstream (``processing_bailingmm2.py::__call__``): when
``images`` is provided the image_processor runs → pixel_values + image_grid_thw,
and ``_expand_image_tokens`` expands ``<IMAGE>`` placeholders in the text
to ``<imagePatch>*N``. The same PIL then ALSO goes to the diffusion stage
as ``image_gen_pixel_values_reference``.
On vllm-omni's serving path serving_chat emits
``multi_modal_data={"img2img": PIL}`` (Bagel convention). We mutate the
caller's mm_data dict here — moving the PIL from the ``img2img`` key into
the ``image`` key — so that:
* vLLM's renderer validator sees consistent keys in
``mm_data`` and the parser output (``mm_data_items["image"]``)
* The thinker-side image path (``_call_hf_processor`` reads
``mm_data["images"]``, ``_get_prompt_updates`` replaces ``<IMAGE>``
placeholders, ``_get_mm_fields_config`` declares image field layout)
all run normally with the ref PIL acting as a regular image input
* ``thinker2imagegen`` still finds the ref PIL — but now under
``multi_modal_data["image"]`` rather than ``["img2img"]``.
A companion prepend in ``_apply_hf_processor_main`` ensures the prompt
text carries a matching ``<IMAGE>`` placeholder when needed.
"""
def parse_mm_data(self, mm_data):
if "img2img" in mm_data:
img2img = mm_data.pop("img2img")
if not isinstance(img2img, list):
img2img = [img2img]
existing = mm_data.get("image")
if existing is None:
existing_list: list[Any] = []
elif isinstance(existing, list):
existing_list = list(existing)
else:
existing_list = [existing]
mm_data["image"] = existing_list + img2img
return super().parse_mm_data(mm_data)
class MingFlashOmniThinkerDummyInputsBuilder(BaseDummyInputsBuilder[MingFlashOmniThinkerProcessingInfo]):
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
num_images = mm_counts.get("image", 0)
@@ -185,6 +238,8 @@ class MingFlashOmniThinkerDummyInputsBuilder(BaseDummyInputsBuilder[MingFlashOmn
audio_length = int(audio_duration * sample_rate)
num_img2img = mm_counts.get("img2img", 0)
mm_data: MultiModalDataDict = {
"image": self._get_dummy_images(
width=image_width,
@@ -200,6 +255,13 @@ class MingFlashOmniThinkerDummyInputsBuilder(BaseDummyInputsBuilder[MingFlashOmn
"audio": [(np.random.randn(audio_length).astype(np.float32), sample_rate) for _ in range(num_audios)],
}
if num_img2img > 0:
mm_data["img2img"] = self._get_dummy_images(
width=image_width,
height=image_height,
num_images=num_img2img,
)
return mm_data
@@ -396,6 +458,61 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
) -> bool:
return False
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,
):
"""Apply Ming-specific prompt rewrites before delegating to vllm's
default text / multimodal processing pipeline.
This is the single point in the base MM-processor call graph where we
still have BOTH the full prompt and the request-level
``hf_processor_mm_kwargs`` together. Downstream, vllm's MM caching
design splits the work into
:meth:`_apply_hf_processor_text_only` (prompt, empty kwargs) and
:meth:`_apply_hf_processor_mm_only` (dummy text, real kwargs), so a
per-request flag like ``modalities`` cannot reach the real
tokenization from inside :meth:`_call_hf_processor`.
For Ming-flash-omni-2.0, image-generation requests carry
``mm_processor_kwargs["modalities"]`` set to ``["image"]`` (t2i) or
``["img2img"]`` (image edit). We expand the prompt here with the
``<image><imagePatch>*N</image>`` query-token block so the expanded
form flows through both the tokenization and (eventual) MM paths.
For img2img, we also prepend ``<IMAGE>`` so the thinker-side prompt
replacement can locate the reference-image placeholder.
"""
modalities = hf_processor_mm_kwargs.get("modalities") or []
is_image_gen = "image" in modalities or "img2img" in modalities
if isinstance(prompt, str) and is_image_gen:
from vllm_omni.model_executor.models.ming_flash_omni.prompt_utils import (
DEFAULT_NUM_QUERY_TOKENS,
maybe_expand_image_gen_prompt,
)
# img2img: prepend ``<IMAGE>`` so the ref-image placeholder survives
# MM caching (when the ref image is cache-warm, the thinker sees 0
# missing items and cannot inject the placeholder itself).
if "img2img" in modalities:
prompt = "<IMAGE>" + prompt
ig = getattr(self.info.ctx.model_config.hf_config, "image_gen_config", None)
num_query_tokens = getattr(ig, "num_query_tokens", DEFAULT_NUM_QUERY_TOKENS)
prompt = maybe_expand_image_gen_prompt(prompt, num_query_tokens=int(num_query_tokens))
return super()._apply_hf_processor_main(
prompt=prompt,
mm_items=mm_items,
hf_processor_mm_kwargs=hf_processor_mm_kwargs,
tokenization_kwargs=tokenization_kwargs,
enable_hf_prompt_update=enable_hf_prompt_update,
)
def _call_hf_processor(
self,
prompt: str,
@@ -408,6 +525,11 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
We call the image/audio sub-processors directly (instead of going
through `MingFlashOmniProcessor.__call__`) so that the high-level
placeholder tokens remain **unexpanded** in the tokenized output.
NOTE: Image-gen prompt expansion is handled in
:meth:`_apply_hf_processor_main` — by the time we get here, vllm's
MM caching has already split text/mm processing and ``mm_kwargs``
is empty on the text-only branch.
"""
hf_processor = self.info.get_hf_processor()
tokenizer = self.info.get_tokenizer()
@@ -425,6 +547,8 @@ class MingFlashOmniThinkerMultiModalProcessor(BaseMultiModalProcessor[MingFlashO
videos = mm_data.get("videos", None)
if videos is not None:
# TODO: ``videos=`` on image_processor is deprecated since
# transformers v4.57 (removed in v5); migrate to Qwen2VLVideoProcessor.
video_outputs = hf_processor.image_processor(
images=None,
videos=videos,
@@ -487,8 +611,13 @@ class MingFlashOmniThinkerForConditionalGeneration(
return "<VIDEO>"
elif modality.startswith("audio"):
return "<AUDIO>"
elif modality == "img2img":
# Ming's img2img ref image is consumed only by the diffusion stage
# (``thinker2imagegen`` reads the raw PIL). No text-side placeholder
# is emitted for the thinker.
return None
raise ValueError("Only image, video, or audio modality is supported")
raise ValueError("Only image, video, audio, or img2img modality is supported")
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
@@ -548,10 +677,79 @@ class MingFlashOmniThinkerForConditionalGeneration(
)
logger.info("Initialized WhisperAudioEncoder and AudioProjector")
# Image-generation learnable query tokens. Stored as a ParameterDict
# keyed by scale name (e.g. "16x16" -> [256, hidden_size]) to mirror
# the upstream Ming layout in ``mlp/query_tokens_dict.<scale>``. These
# are substituted in at ``<imagePatch>`` token positions during
# text-to-image requests; image-comprehension requests continue to
# fill those positions with vision features as before.
self.query_tokens_dict = nn.ParameterDict()
self._load_image_gen_query_tokens(vllm_config.model_config.model)
# Expose interfaces
self.make_empty_intermediate_tensors = self.language_model.make_empty_intermediate_tensors
logger.info("MingFlashOmniThinker initialized with vision and audio towers")
logger.info(
f"MingFlashOmniThinker initialized with: "
f"vision={'yes' if self.vision else 'no'}, "
f"audio={'yes' if self.audio else 'no'}, "
f"image_gen_scales={list(self.query_tokens_dict.keys())}"
)
def _load_image_gen_query_tokens(self, model_path: str) -> None:
"""Load learnable query tokens used for image generation.
Expected layout (observed on inclusionAI/Ming-flash-omni-2.0):
<model_path>/mlp/model.safetensors
key ``query_tokens_dict.<scale>`` -> [num_tokens, hidden_size]
e.g. ``query_tokens_dict.16x16`` -> [256, 4096]
Missing files are logged as a warning and image-gen is disabled
(text-only inference still works).
"""
from pathlib import Path
p = Path(model_path) / "mlp" / "model.safetensors"
if not p.exists() and not os.path.exists(model_path):
from vllm_omni.model_executor.model_loader.weight_utils import (
download_weights_from_hf_specific,
)
try:
local_path = download_weights_from_hf_specific(model_path, None, ["mlp/*"])
p = Path(local_path) / "mlp" / "model.safetensors"
except Exception:
logger.exception("[MingFlashOmniThinker] failed to download mlp/ from %s", model_path)
if not p.exists():
logger.warning(
"[MingFlashOmniThinker] mlp/model.safetensors not found at %s; "
"text-to-image will be disabled (text-only inference still works).",
p,
)
return
try:
from safetensors.torch import load_file # type: ignore
state = load_file(str(p))
except Exception:
logger.exception("[MingFlashOmniThinker] failed to read %s", p)
return
loaded = 0
for key, tensor in state.items():
if not key.startswith("query_tokens_dict."):
continue
scale_name = key.split(".", 1)[1]
param = nn.Parameter(tensor.clone(), requires_grad=False)
self.query_tokens_dict[scale_name] = param
loaded += 1
logger.info(
"[MingFlashOmniThinker] loaded query_tokens_dict[%s] shape=%s dtype=%s",
scale_name,
tuple(tensor.shape),
tensor.dtype,
)
if loaded == 0:
logger.warning("[MingFlashOmniThinker] no query_tokens_dict.* keys in mlp/model.safetensors")
def extract_image_feature(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
"""Extract and project image features.
@@ -732,14 +930,86 @@ class MingFlashOmniThinkerForConditionalGeneration(
) -> torch.Tensor:
inputs_embeds = self.language_model.model.word_embeddings(input_ids)
if multimodal_embeddings is None or len(multimodal_embeddings) == 0:
return inputs_embeds
# Step 1: if vision/audio features were extracted, merge them into
# inputs_embeds at their <patch> positions first. This fills ref-image
# and other normal vision-input positions with real features.
if multimodal_embeddings is not None and len(multimodal_embeddings) > 0:
assert is_multimodal is not None, "`is_multimodal` mask required when `multimodal_embeddings` provided"
inputs_embeds = _merge_multimodal_embeddings(
inputs_embeds=inputs_embeds,
multimodal_embeddings=multimodal_embeddings,
is_multimodal=is_multimodal,
)
assert is_multimodal is not None, "`is_multimodal` mask required when `multimodal_embeddings` provided"
return _merge_multimodal_embeddings(
inputs_embeds=inputs_embeds,
multimodal_embeddings=multimodal_embeddings,
is_multimodal=is_multimodal,
# Step 2: image-gen query tokens are appended at the tail of the prompt
# as a contiguous block of ``<imagePatch>`` tokens. Inject the learnable
# ``query_tokens_dict`` entries at those positions. Running AFTER step 1
# is safe because the query-token block is disjoint from ref-image
# patch positions (ref patches are earlier in the prompt, filled by
# step 1; query tokens occupy the trailing block and get overwritten
# here). Injecting always — including when multimodal embeddings are
# present — matches Ming's img2img-edit flow where BOTH a real image
# input AND the learnable query tokens need to reach the LLM.
if len(self.query_tokens_dict) > 0:
self._maybe_inject_image_gen_query_embeds(input_ids, inputs_embeds)
return inputs_embeds
def _maybe_inject_image_gen_query_embeds(
self,
input_ids: torch.Tensor,
inputs_embeds: torch.Tensor,
) -> None:
"""Overwrite the trailing ``<imagePatch>`` block with learnable query tokens.
The image-gen query-token block is appended at the tail of the prompt
by ``maybe_expand_image_gen_prompt`` as literal text
``<image><imagePatch>*N</image>``. After tokenization:
... <image_start_token> <imagePatch>*N <image_end_token>
is the exact trailing pattern. We verify that signature before
injecting — without the check, a pure vision-understanding request
whose final ref-image block ends in N or more ``<imagePatch>`` tokens
would be misidentified as image-gen and its vision features silently
overwritten. Decode-phase calls (``input_ids`` is one next-token)
naturally fail the signature check and return early.
"""
if input_ids.numel() == 0:
return
patch_token_id = self.config.image_patch_token
image_end_token_id = getattr(self.config, "image_end_token", None)
if image_end_token_id is None:
return
scale_items = list(self.query_tokens_dict.items())
if not scale_items:
return
scale_name, query_param = scale_items[-1]
num_query_tokens = int(query_param.shape[0])
flat = input_ids.view(-1)
L = int(flat.numel())
# Need at least num_query_tokens patch tokens + 1 <image_end> token.
if L < num_query_tokens + 1:
return
# Signature: the prompt must end with <image_end_token>, and the
# N positions immediately before it must all be <imagePatch>.
if int(flat[-1].item()) != image_end_token_id:
return
tail_start = L - 1 - num_query_tokens
tail_end = L - 1 # exclusive — last index is <image_end_token>
if not (flat[tail_start:tail_end] == patch_token_id).all():
return
query_embeds = query_param.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
inputs_embeds[tail_start:tail_end] = query_embeds
logger.debug(
"[MingFlashOmniThinker] injected %d image-gen query embeddings (scale=%s) at positions [%d, %d)",
num_query_tokens,
scale_name,
tail_start,
tail_end,
)
def forward(
@@ -3,12 +3,86 @@
# Copyright (c) Ant Group. All rights reserved.
# Adapted from Ming repo's usage cookbook:
# https://github.com/inclusionAI/Ming/blob/3954fcb880ff5e61ff128bcf7f1ec344d46a6fe3/cookbook.ipynb
"""Shared prompt-building helpers for Ming-flash-omni standalone talker."""
"""Ming-flash-omni-2.0 prompt utilities.
Two unrelated families of helpers live in the same file because they
both belong to the Ming module and are tightly coupled to Ming-specific
prompt conventions:
1. **Image-gen query-token expansion** — string-level helpers used by
the thinker stage to mark the ``<image><imagePatch>*N</image>`` block
that gets substituted with learnable ``query_tokens_dict`` embeddings
during forward.
2. **TTS / talker caption builder** — JSON caption template for the
Ming-flash-omni standalone talker (TTS) stage.
"""
from __future__ import annotations
import copy
import json
from typing import Any
# ============================================================
# Image-gen query-token block (thinker stage)
# ============================================================
# Ming's thinker uses these tokens to mark a learnable image-generation
# query block inside the text prompt. The thinker substitutes its
# ``query_tokens_dict`` embeddings at each ``<imagePatch>`` position
# during forward; see
# ``MingFlashOmniThinker._maybe_inject_image_gen_query_embeds``.
_IMAGE_OPEN_TOKEN = "<image>"
_IMAGE_CLOSE_TOKEN = "</image>"
IMAGE_PATCH_TOKEN = "<imagePatch>"
# Default query-token count matches ``MingImageGenConfig(img_gen_scales=[16])``
# (16 * 16 = 256), which is what the released inclusionAI/Ming-flash-omni-2.0
# checkpoint ships.
DEFAULT_NUM_QUERY_TOKENS = 256
def maybe_expand_image_gen_prompt(
prompt: str,
num_query_tokens: int = DEFAULT_NUM_QUERY_TOKENS,
) -> str:
"""Append the ``<image><imagePatch>*N</image>`` suffix for text-to-image.
The thinker expects image-generation requests to end with an N-wide
block of ``<imagePatch>`` tokens (wrapped in ``<image>``/``</image>``)
— those positions get substituted with learnable
``query_tokens_dict`` embeddings during forward.
This helper is a no-op (returns the input unchanged) when:
* ``prompt`` is not a non-empty string, or
* the prompt already contains an ``<imagePatch>`` block (avoids
double expansion for tests / manual calls that pre-format the
prompt).
Args:
prompt: Raw user prompt text.
num_query_tokens: Total number of query tokens to emit. Defaults
to 256 (the released checkpoint's ``img_gen_scales=[16]``).
Returns:
The (possibly expanded) prompt text.
"""
if not isinstance(prompt, str) or not prompt:
return prompt
if IMAGE_PATCH_TOKEN in prompt:
return prompt
# TODO(multi-scale): single-block emission assumes img_gen_scales=[16].
suffix = _IMAGE_OPEN_TOKEN + (IMAGE_PATCH_TOKEN * num_query_tokens) + _IMAGE_CLOSE_TOKEN
return prompt + suffix
# ============================================================
# TTS / talker caption builder
# ============================================================
DEFAULT_PROMPT = "Please generate speech based on the following description.\n"
BASE_CAPTION_TEMPLATE: dict[str, Any] = {
@@ -48,3 +122,13 @@ def create_instruction(user_input: dict[str, Any]) -> str:
if key in item:
item[key] = value
return json.dumps(caption, ensure_ascii=False)
__all__ = [
"IMAGE_PATCH_TOKEN",
"DEFAULT_NUM_QUERY_TOKENS",
"maybe_expand_image_gen_prompt",
"DEFAULT_PROMPT",
"BASE_CAPTION_TEMPLATE",
"create_instruction",
]
@@ -0,0 +1,98 @@
# Dual-stage single-node deployment of Ming-flash-omni-2.0 text-to-image.
#
# Stage 0 (thinker, llm): BailingMoeV2 LLM + vision/audio encoders, TP=2
# on cards 0 and 1. Detects text-to-image requests
# (auto-appended with <image><imagePatch>*256</image>
# by serving_chat), replaces those positions with
# learnable ``query_tokens_dict`` embeddings, runs
# forward, and exports the final-layer hidden states
# under ``multimodal_output["final_hidden_states"]``.
#
# Stage 1 (imagegen, diffusion): Qwen2 connector + ZImage DiT + VAE, TP=1 on
# card 3. Consumes the thinker hidden states
# shipped from stage 0 (sliced at <imagePatch>
# positions by ``thinker2imagegen``) as DiT
# conditioning, runs the Ming condition
# encoder + 30-step FlowMatchEuler denoise
# + VAE decode, emits a raw image tensor.
#
# Cross-stage transport: ``shared_memory_connector`` (intra-node). The
# thinker's ``multimodal_output`` flows automatically; ``thinker2imagegen``
# (custom_process_input_func) slices it and produces a list[dict] with the
# conditioning tensor under ``extra[thinker_hidden_states]``. Msgpack
# (``OmniMsgpackEncoder``) handles bf16/fp16 tensors natively.
#
# TODO(ming-flash-omni-2.0): stage 0 `thinker_config` / stage 1 `image_gen_config` target the
# future unified MingFlashOmniConfig; today's BailingMM2Config checkpoint silently falls back.
stage_args:
- stage_id: 0
stage_type: llm
# CFG prompt expansion: when a request carries ``negative_prompt``, one
# companion is spawned so both positive and negative hidden states reach
# the diffusion stage (consumed by MingImagePipeline as real CFG negatives).
prompt_expand_func: vllm_omni.model_executor.stage_input_processors.ming_flash_omni.expand_cfg_prompts
hf_config_name: thinker_config
runtime:
devices: "0,1,2,3"
engine_args:
model_stage: thinker
max_num_seqs: 2 # parent + 1 CFG-text companion (negative prompt)
model_arch: MingFlashOmniForConditionalGeneration
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
gpu_memory_utilization: 0.85
enforce_eager: true
trust_remote_code: true
engine_output_type: latent
distributed_executor_backend: "mp"
enable_prefix_caching: false
tensor_parallel_size: 4
is_comprehension: true
default_sampling_params:
temperature: 0.4
top_p: 0.9
top_k: 1
max_tokens: 1 # image-gen request: prefill only, no AR decode
seed: 42
detokenize: false
output_connectors:
to_stage_1: shared_memory_connector
- stage_id: 1
stage_type: diffusion
hf_config_name: image_gen_config
runtime:
devices: "4"
engine_args:
model_stage: dit
model_arch: MingImagePipeline # resolved in vllm_omni/diffusion/registry.py
enforce_eager: true
trust_remote_code: true
distributed_executor_backend: "mp"
engine_input_source: [0]
custom_process_input_func: vllm_omni.model_executor.stage_input_processors.ming_flash_omni.thinker2imagegen
final_output: true
final_output_type: image
is_comprehension: false
default_sampling_params:
seed: 42
input_connectors:
from_stage_0: shared_memory_connector
runtime:
enabled: true
defaults:
window_size: -1
max_inflight: 1
connectors:
shared_memory_connector:
name: SharedMemoryConnector
extra:
shm_threshold_bytes: 65536 # 64KB threshold
edges:
- from: 0
to: 1
window_size: -1
@@ -4,27 +4,458 @@
from __future__ import annotations
import logging
import re
from dataclasses import dataclass
from typing import Any
import torch
from vllm.inputs import TextPrompt
from vllm_omni.inputs.data import OmniTokensPrompt
logger = logging.getLogger(__name__)
CFG_TEXT_SUFFIX = "__cfg_text"
# Fallback when stage config introspection fails; matches
# llm_config.image_patch_token on the released Ming-flash-omni-2.0 checkpoint.
_DEFAULT_IMAGE_PATCH_TOKEN_ID = 157157
# Ming's byte5 glyph text is auto-extracted from the user prompt's quoted
# spans (ASCII double quotes / Chinese curly quotes). Patterns and regex
# taken verbatim from Ming ``processing_bailingmm2.py::get_text_from_prompt``.
_GLYPH_QUOTE_PATTERNS = [r"\"(.*?)\"", r"‘(.*?)’", r"“(.*?)”"]
_GLYPH_REMOVE_KEYWORDS = ("remove", "delete", "erase")
def _check_single_quotes(s: str) -> bool:
"""Decide whether ASCII single quotes in ``s`` act as glyph delimiters.
Mirrors Ming's heuristic: count Chinese chars as weight 3, others as 1;
if any paired-single-quote span crosses weight 20 we assume the quotes are
apostrophes (e.g. "don't"), not glyph markers.
"""
if s.count("'") % 2 != 0:
return False
positions = [i for i, ch in enumerate(s) if ch == "'"]
for i in range(0, len(positions), 2):
start, end = positions[i], positions[i + 1]
inner = s[start + 1 : end]
chinese = sum(1 for c in inner if "\u4e00" <= c <= "\u9fff")
total = 3 * chinese + (len(inner) - chinese)
if total >= 20:
return False
return True
def _extract_byte5_glyph_text(prompt: str) -> str:
"""Return ``Ming``-style ``'Text "<glyph>". '`` or ``""`` when no glyph."""
if not isinstance(prompt, str) or not prompt:
return ""
if "'" in prompt and _check_single_quotes(prompt):
prompt = prompt.replace("'", '"')
texts: list[str] = []
for pattern in _GLYPH_QUOTE_PATTERNS:
texts.extend(re.findall(pattern, prompt))
if len(texts) == 1:
# Treat "remove/delete/erase ..." as a glyph-removal intent, not generation.
text_start = min(
(prompt.find(q) for q in ('"', "‘", "“") if prompt.find(q) >= 0),
default=-1,
)
lower = prompt.lower()
for kw in _GLYPH_REMOVE_KEYWORDS:
idx = lower.find(kw)
if 0 <= idx < text_start:
return ""
if not texts:
return ""
# Only the last quoted span is used (Ming's choice; keeps the most recent edit target).
return f'Text "{texts[-1]}". '
# ---------------------------------------------------------------------------
# CFG prompt expansion (stage 0: prompt_expand_func)
# ---------------------------------------------------------------------------
@dataclass
class _CfgExpandedPrompt:
"""Minimal structural object consumed by ``AsyncOmniEngine._enqueue_cfg_companions``."""
prompt: dict[str, Any]
role: str
request_id_suffix: str
def apply_overrides(self, base_params: Any, base_spl: list[Any]) -> tuple[Any, list[Any]]:
return base_params, base_spl
def expand_cfg_prompts(
prompt: dict[str, Any] | str,
sampling_params: Any,
) -> list[_CfgExpandedPrompt]:
"""Expand a text-to-image request into one CFG-text companion (opt-in).
Triggers only when a non-empty
``sampling_params.extra_args["image_gen"]["negative_prompt"]`` is set on
the stage-0 params; otherwise returns ``[]`` and the pipeline falls back
to zero negative (Ming's default behavior).
"""
if not isinstance(prompt, dict):
return []
if prompt.get("modalities") != ["image"]:
return []
extra_args = getattr(sampling_params, "extra_args", None) or {}
image_gen_args = extra_args.get("image_gen") or {}
negative = image_gen_args.get("negative_prompt")
if not isinstance(negative, str) or not negative.strip():
return []
neg_prompt_dict: dict[str, Any] = {
"prompt": negative,
"modalities": prompt.get("modalities"),
}
mm_kwargs = prompt.get("mm_processor_kwargs")
if mm_kwargs:
neg_prompt_dict["mm_processor_kwargs"] = dict(mm_kwargs)
return [_CfgExpandedPrompt(prompt=neg_prompt_dict, role="cfg_text", request_id_suffix=CFG_TEXT_SUFFIX)]
# ---------------------------------------------------------------------------
# Thinker → imagegen bridge (stage 1: custom_process_input_func)
# ---------------------------------------------------------------------------
def _resolve_num_query_tokens(stage: Any) -> int | None:
"""Return the image-gen ``num_query_tokens`` from the source stage's config.
Falls back to 256 (``img_gen_scales=[16]``) when the stage config lacks
a ``MingImageGenConfig``. Cached on the stage object for O(1) re-reads.
"""
cached = getattr(stage, "_ming_num_query_tokens", None)
if isinstance(cached, int):
return cached
n = 256 # Ming-flash-omni-2.0 default (img_gen_scales=[16])
try:
hf_config = stage.vllm_config.model_config.hf_config
ig = getattr(hf_config, "image_gen_config", None)
resolved = getattr(ig, "num_query_tokens", None)
if isinstance(resolved, int) and resolved > 0:
n = resolved
except AttributeError:
pass
try:
stage._ming_num_query_tokens = n
except AttributeError:
pass
return n
def _resolve_image_end_token_id(stage: Any) -> int | None:
"""Return the ``<image_end>`` token id from *stage*'s HF config, cached on first call."""
cached = getattr(stage, "_image_end_token_id", None)
if isinstance(cached, int):
return cached
token_id: int | None = None
try:
hf_config = stage.vllm_config.model_config.hf_config
llm_config = getattr(hf_config, "llm_config", None)
resolved = getattr(llm_config, "image_end_token", None)
if isinstance(resolved, int):
token_id = resolved
except AttributeError:
pass
try:
stage._image_end_token_id = token_id
except AttributeError:
pass
return token_id
def _resolve_image_patch_token_id(stage: Any) -> int:
"""Return the ``<imagePatch>`` token id from *stage*'s HF config, cached on first call."""
cached = getattr(stage, "_image_patch_token_id", None)
if isinstance(cached, int):
return cached
token_id = _DEFAULT_IMAGE_PATCH_TOKEN_ID
try:
hf_config = stage.vllm_config.model_config.hf_config
llm_config = getattr(hf_config, "llm_config", None)
resolved = getattr(llm_config, "image_patch_token", None)
if isinstance(resolved, int):
token_id = resolved
except AttributeError:
pass
try:
stage._image_patch_token_id = token_id
except AttributeError:
pass
return token_id
def _validate_stage_inputs(stage_list, engine_input_source):
"""Validate stage inputs and return the source engine outputs."""
if not engine_input_source:
raise ValueError("engine_input_source cannot be empty")
stage_id = engine_input_source[0]
if stage_id >= len(stage_list):
raise IndexError(f"Invalid stage_id: {stage_id}")
stage = stage_list[stage_id]
if stage.engine_outputs is None:
raise RuntimeError(f"Stage {stage_id} has no outputs yet")
return stage, stage.engine_outputs
return stage.engine_outputs
def _ensure_list(x) -> list[int]:
"""Convert ConstantList / tensor-like to plain list."""
if hasattr(x, "_x"):
return list(x._x)
if isinstance(x, list):
return x
if hasattr(x, "tolist"):
return x.tolist()
return list(x)
def _slice_patch_hidden(
thinker_output: Any,
image_patch_token_id: int,
tag: str,
num_query_tokens: int | None = None,
image_end_token_id: int | None = None,
) -> torch.Tensor | None:
"""Return ``[N, H]`` hidden at the image-gen query-token block.
The image-gen block is always appended at the prompt tail as
``<image_start><imagePatch>*N<image_end>`` by
``maybe_expand_image_gen_prompt``. We find the exact trailing window by
anchoring on the final ``image_end_token`` and walking back N positions,
verifying they're all ``image_patch_token``. Without that signature check
we'd risk slicing ref-image patches (img2img case) or comprehension-only
patch blocks.
Falls back to "all patch positions" if ``image_end_token_id`` or
``num_query_tokens`` is not provided — matches the pre-img2img t2i-only
behavior used by older callers.
"""
output = thinker_output.outputs[0]
mm_out = getattr(output, "multimodal_output", None) or {}
full_hidden = mm_out.get("final_hidden_states")
if full_hidden is None:
logger.warning("[thinker2imagegen] %s: missing final_hidden_states (keys=%s)", tag, list(mm_out.keys()))
return None
prompt_ids = _ensure_list(thinker_output.prompt_token_ids)
prompt_ids_t = torch.tensor(prompt_ids, dtype=torch.long, device=full_hidden.device)
patch_indices = (prompt_ids_t == image_patch_token_id).nonzero(as_tuple=False).squeeze(-1)
total_patches = int(patch_indices.numel())
if total_patches == 0:
logger.warning("[thinker2imagegen] %s: no <imagePatch> tokens in prompt (len=%d)", tag, len(prompt_ids))
return None
if full_hidden.dim() == 3:
assert full_hidden.shape[0] == 1, f"expected batch=1, got {full_hidden.shape}"
full_hidden = full_hidden[0]
if full_hidden.dim() != 2 or full_hidden.shape[0] != prompt_ids_t.shape[0]:
logger.warning(
"[thinker2imagegen] %s: hidden shape %s inconsistent with prompt len %d",
tag,
tuple(full_hidden.shape),
prompt_ids_t.shape[0],
)
return None
selected_indices = patch_indices
if num_query_tokens is not None and image_end_token_id is not None:
L = int(prompt_ids_t.numel())
if L >= num_query_tokens + 1 and int(prompt_ids_t[-1].item()) == image_end_token_id:
tail_start = L - 1 - num_query_tokens
tail_end = L - 1 # exclusive
tail_slice = prompt_ids_t[tail_start:tail_end]
if (tail_slice == image_patch_token_id).all():
selected_indices = torch.arange(tail_start, tail_end, dtype=torch.long, device=full_hidden.device)
else:
logger.warning(
"[thinker2imagegen] %s: tail signature mismatch (expected N patches "
"before <image_end>); falling back to all patch positions",
tag,
)
else:
logger.warning(
"[thinker2imagegen] %s: image-gen block signature not found at prompt tail "
"(len=%d, last_tok=%s); falling back to all patch positions",
tag,
L,
int(prompt_ids_t[-1].item()) if L else None,
)
hidden = full_hidden[selected_indices].detach().contiguous()
if logger.isEnabledFor(logging.DEBUG):
f = hidden.float()
logger.debug(
"[thinker2imagegen] %s sliced=%s (%d of %d patches) mean=%+.4f std=%.4f |x|/tok=%.3f",
tag,
tuple(hidden.shape),
int(selected_indices.numel()),
total_patches,
f.mean().item(),
f.std().item(),
f.norm(dim=-1).mean().item(),
)
return hidden
def _resolve_token_ids_from_stage_or_defaults(
stage: Any | None,
) -> tuple[int, int | None, int | None]:
"""Return (image_patch_token_id, image_end_token_id, num_query_tokens).
Tries to read from the stage's HF config when available (old API).
Falls back to Ming-flash-omni-2.0 defaults when stage is None (new API).
"""
if stage is not None:
return (
_resolve_image_patch_token_id(stage),
_resolve_image_end_token_id(stage),
_resolve_num_query_tokens(stage),
)
# Defaults from Ming-flash-omni-2.0:
# llm_config.image_patch_token = 157157
# llm_config.image_end_token = 157159
# img_gen_scales=[16] -> 16*16 = 256 query tokens
return (_DEFAULT_IMAGE_PATCH_TOKEN_ID, 157159, 256)
def _extract_byte5_from_sampling_params(sampling_params: Any) -> list[str] | None:
"""Read ``byte5_text`` from the diffusion-stage sampling_params.
Looks up ``sampling_params.extra_args["image_gen"]["byte5_text"]`` (the
explicit API surface for ByT5 glyph text). Returns ``None`` if absent or
malformed, so callers can fall back to other sources.
"""
if sampling_params is None:
return None
extra = getattr(sampling_params, "extra_args", None)
if not isinstance(extra, dict):
return None
image_gen = extra.get("image_gen")
if not isinstance(image_gen, dict):
return None
texts = image_gen.get("byte5_text")
if isinstance(texts, list) and texts:
return [t for t in texts if isinstance(t, str)]
return None
def thinker2imagegen(
source_outputs: list[Any],
prompt: Any | None = None,
requires_multimodal_data: bool = False, # noqa: ARG001
sampling_params: Any | None = None,
) -> list[dict[str, Any]]:
"""Bridge thinker AR outputs into image-generation DiT inputs.
The orchestrator passes ``source_outputs`` as
``[parent_output, *companion_outputs]``. Parent outputs feed
``extra[thinker_hidden_states]``; the cfg_text companion feeds
``extra[negative_thinker_hidden_states]`` used by MingImagePipeline as real
CFG negative conditioning. Unknown-suffix outputs are skipped.
``sampling_params`` is the diffusion stage's own SamplingParams, supplied
by the orchestrator. ByT5 explicit ``byte5_text`` is read from
``sampling_params.extra_args.image_gen.byte5_text`` (preferred); falls
back to ``prompt.image_gen_extra_args.byte5_text``, then to auto-extraction
from quoted prompt text.
"""
thinker_outputs = source_outputs
image_patch_token_id, image_end_token_id, num_query_tokens = _resolve_token_ids_from_stage_or_defaults(stage=None)
parent_output = None
negative_output = None
for o in thinker_outputs:
rid = getattr(o, "request_id", "")
if rid.endswith(CFG_TEXT_SUFFIX):
negative_output = o
elif parent_output is None:
parent_output = o
if parent_output is None:
logger.warning("[thinker2imagegen] no parent output in engine_outputs; skipping")
return []
parent_hidden = _slice_patch_hidden(
parent_output,
image_patch_token_id,
tag="parent",
num_query_tokens=num_query_tokens,
image_end_token_id=image_end_token_id,
)
if parent_hidden is None:
return []
extra: dict[str, Any] = {"thinker_hidden_states": parent_hidden}
if negative_output is not None:
neg_hidden = _slice_patch_hidden(
negative_output,
image_patch_token_id,
tag="cfg_text",
num_query_tokens=num_query_tokens,
image_end_token_id=image_end_token_id,
)
if neg_hidden is not None:
extra["negative_thinker_hidden_states"] = neg_hidden
# img2img: forward the reference image PIL/tensor to the diffusion stage.
if isinstance(prompt, dict):
mm_data = prompt.get("multi_modal_data") or {}
ref_image = mm_data.get("image")
if isinstance(ref_image, list) and ref_image:
ref_image = ref_image[0]
if ref_image is None:
ref_image = mm_data.get("img2img")
if isinstance(ref_image, list) and ref_image:
ref_image = ref_image[0]
if ref_image is not None:
extra["reference_image"] = ref_image
# ByT5 glyph text: prefer sampling_params (stage-1 explicit API), then
# prompt.image_gen_extra_args (serving_chat path), then auto-extract
# from quoted prompt text.
prompt_text = prompt.get("prompt", "")
sp_byte5 = _extract_byte5_from_sampling_params(sampling_params)
if sp_byte5:
byte5_texts: list[str] | None = sp_byte5
else:
ig_extra = prompt.get("image_gen_extra_args") or {}
cand = ig_extra.get("byte5_text")
byte5_texts = cand if isinstance(cand, list) and cand else None
if byte5_texts:
extra["byte5_text"] = [
t if t.startswith("Text ") else f'Text "{t}". ' for t in byte5_texts if isinstance(t, str)
]
else:
glyph = _extract_byte5_glyph_text(prompt_text)
if glyph:
extra["byte5_text"] = [glyph]
else:
# prompt is not a dict — still honor explicit byte5_text from sampling_params.
sp_byte5 = _extract_byte5_from_sampling_params(sampling_params)
if sp_byte5:
extra["byte5_text"] = [t if t.startswith("Text ") else f'Text "{t}". ' for t in sp_byte5]
return [{"prompt": "", "extra": extra}]
def thinker2talker(
@@ -39,7 +470,7 @@ def thinker2talker(
a talker input prompt with the text and any speaker/instruction info
from the original request.
"""
source_outputs = _validate_stage_inputs(stage_list, engine_input_source)
_, source_outputs = _validate_stage_inputs(stage_list, engine_input_source)
if not isinstance(prompt, list):
prompt = [prompt]
@@ -102,3 +533,11 @@ def thinker2talker(
)
return talker_inputs
__all__ = [
"CFG_TEXT_SUFFIX",
"expand_cfg_prompts",
"thinker2imagegen",
"thinker2talker",
]