[Model] Migrate MammothModa2-Preview example to standard task example + model_extras (#4691)
Signed-off-by: mo saif <moisf56@gmail.com> Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
11f6a0b72e
commit
2fc00efa49
12 files changed
+415
-326
No files matched your search
@@ -142,6 +142,43 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
|
||||
dtype=dtype,
|
||||
)
|
||||
|
||||
def _split_ar_conditions(
|
||||
self,
|
||||
*,
|
||||
full_hidden_states: torch.Tensor,
|
||||
full_token_ids: list[int],
|
||||
answer_start_index: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Split AR-stage hidden states into text / image condition embeds.
|
||||
|
||||
The token ids that distinguish question (text) tokens, generated visual
|
||||
tokens, and multi-modal placeholder tokens are read from the model config
|
||||
(``gen_vocab_start_index`` and the vision placeholder token ids), so the
|
||||
caller no longer needs to pass them. Mirrors the masking the bespoke
|
||||
MammothModa2 example performed via ar2dit.
|
||||
"""
|
||||
gen_vocab_start_index = int(self.config.llm_config.gen_vocab_start_index)
|
||||
visual_ids = [
|
||||
int(self.config.image_token_id),
|
||||
int(self.config.video_token_id),
|
||||
int(self.config.vision_start_token_id),
|
||||
int(self.config.vision_end_token_id),
|
||||
]
|
||||
|
||||
device = full_hidden_states.device
|
||||
token_ids = torch.tensor(full_token_ids, dtype=torch.long, device=device)
|
||||
positions = torch.arange(token_ids.shape[0], device=device)
|
||||
questions_mask = positions < answer_start_index
|
||||
answers_mask = ~questions_mask
|
||||
gen_token_mask = token_ids >= gen_vocab_start_index
|
||||
visual_token_mask = torch.isin(token_ids, torch.tensor(visual_ids, dtype=torch.long, device=device))
|
||||
text_mask = questions_mask & ~(visual_token_mask | gen_token_mask)
|
||||
image_mask = answers_mask & gen_token_mask
|
||||
|
||||
text_cond = full_hidden_states[text_mask].to(dtype=torch.float32).contiguous()
|
||||
image_cond = full_hidden_states[image_mask].to(dtype=torch.float32).contiguous()
|
||||
return text_cond, image_cond
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(
|
||||
self,
|
||||
@@ -151,14 +188,35 @@ class MammothModa2DiTPipeline(nn.Module, SupportsComponentDiscovery):
|
||||
) -> OmniOutput:
|
||||
runtime_addi = kwargs.get("runtime_additional_information", None)
|
||||
info = runtime_addi[0]
|
||||
text_cond = info["text_prompt_embeds"]
|
||||
image_cond = info["image_prompt_embeds"]
|
||||
|
||||
# Sampling knobs are declared in vllm_omni/model_extras/mammothmodal2_preview.py
|
||||
# and routed via extra_body -> sampling_params.extra_args (surfaced here as
|
||||
# ``sampling_extra_args``). Fall back to runtime_additional_information for the
|
||||
# legacy bespoke-example path during the transition.
|
||||
extra_args_list = kwargs.get("sampling_extra_args") or []
|
||||
extra_args = extra_args_list[0] if extra_args_list else {}
|
||||
text_guidance_scale = float(extra_args.get("text_guidance_scale", info["text_guidance_scale"][0]))
|
||||
cfg_range_val = extra_args.get("cfg_range", info["cfg_range"])
|
||||
cfg_range = float(cfg_range_val[0]), float(cfg_range_val[1])
|
||||
num_inference_steps = int(extra_args.get("num_inference_steps", info["num_inference_steps"][0]))
|
||||
|
||||
negative_cond = info.get("negative_prompt_embeds")
|
||||
negative_attention_mask = info.get("negative_prompt_attention_mask")
|
||||
image_hw = info["image_height"][0], info["image_width"][0]
|
||||
text_guidance_scale = info["text_guidance_scale"][0]
|
||||
cfg_range = info["cfg_range"][0], info["cfg_range"][1]
|
||||
num_inference_steps = info["num_inference_steps"][0]
|
||||
|
||||
# Split the AR hidden states into text / image conditions. The token ids that
|
||||
# drive the split are sourced from the model config (see _split_ar_conditions),
|
||||
# formerly supplied by the bespoke example via additional_information. Legacy
|
||||
# fallback: ar2dit may have already produced the split conditions.
|
||||
if "text_prompt_embeds" in info:
|
||||
text_cond = info["text_prompt_embeds"]
|
||||
image_cond = info["image_prompt_embeds"]
|
||||
else:
|
||||
text_cond, image_cond = self._split_ar_conditions(
|
||||
full_hidden_states=info["full_hidden_states"],
|
||||
full_token_ids=info["full_token_ids"],
|
||||
answer_start_index=int(info["answer_start_index"][0]),
|
||||
)
|
||||
|
||||
# Move to model device/dtype.
|
||||
model_device = next(self.parameters()).device
|
||||
|
||||
@@ -36,6 +36,15 @@ stage_args:
|
||||
trust_remote_code: true
|
||||
engine_output_type: image
|
||||
enable_prefix_caching: false
|
||||
# Declares extra_args so has_sampling_extra_args is enabled, routing the t2i knobs
|
||||
# (text_guidance_scale, cfg_range, num_inference_steps) declared in
|
||||
# vllm_omni/model_extras/mammothmodal2_preview.py from extra_body into the DiT
|
||||
# forward. Values here are the defaults applied when a request omits a knob.
|
||||
default_sampling_params:
|
||||
extra_args:
|
||||
text_guidance_scale: 9.0
|
||||
cfg_range: [0.0, 1.0]
|
||||
num_inference_steps: 50
|
||||
engine_input_source: [0]
|
||||
custom_process_input_func: vllm_omni.model_executor.stage_input_processors.mammoth_moda2.ar2dit
|
||||
final_output: true
|
||||
|
||||
@@ -3,12 +3,34 @@
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.inputs import TextPrompt
|
||||
|
||||
from vllm_omni.inputs.data import OmniTokensPrompt
|
||||
|
||||
|
||||
def _as_dict(prompt: Any) -> dict[str, Any]:
|
||||
"""Coerce an original-stage prompt to a dict.
|
||||
|
||||
It may arrive as a dict, a NamedTuple/object, or a bare string depending on
|
||||
the calling flow (the shared text_to_image example vs the bespoke script).
|
||||
"""
|
||||
if isinstance(prompt, dict):
|
||||
return prompt
|
||||
if hasattr(prompt, "_asdict"):
|
||||
return prompt._asdict()
|
||||
if hasattr(prompt, "__dict__"):
|
||||
return vars(prompt)
|
||||
return {}
|
||||
|
||||
|
||||
def _coerce_dim(value: Any, default: int) -> int:
|
||||
try:
|
||||
iv = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return iv if iv > 0 else default
|
||||
|
||||
|
||||
def ar2dit(
|
||||
source_outputs: list[Any],
|
||||
prompts: OmniTokensPrompt | TextPrompt | list[OmniTokensPrompt | TextPrompt] | None = None,
|
||||
@@ -17,21 +39,33 @@ def ar2dit(
|
||||
"""Convert AR stage outputs to DiT stage inputs."""
|
||||
ar_outputs = source_outputs
|
||||
|
||||
# Normalize prompts to list
|
||||
# The shared text_to_image example forwards a single prompt (not a list); normalize
|
||||
# so a lone dict isn't iterated as its keys. Mirrors glm_image.ar2diffusion.
|
||||
if not isinstance(prompts, list):
|
||||
prompts = [prompts] if prompts is not None else [{}]
|
||||
|
||||
dit_inputs: list[OmniTokensPrompt] = []
|
||||
for ar_output, prompt in zip(ar_outputs, prompts):
|
||||
addi_info = prompt["additional_information"]
|
||||
image_height = addi_info["image_height"][0]
|
||||
image_width = addi_info["image_width"][0]
|
||||
text_guidance_scale = addi_info["text_guidance_scale"][0]
|
||||
cfg_range = addi_info["cfg_range"]
|
||||
num_inference_steps = addi_info["num_inference_steps"][0]
|
||||
gen_vocab_start_index = addi_info["visual_token_start_id"][0]
|
||||
# ["<|image_pad|>", "<|video_pad|>", "<|vision_start|>", "<|vision_end|>"]
|
||||
visual_ids = addi_info["visual_ids"]
|
||||
for i, ar_output in enumerate(ar_outputs):
|
||||
prompt_dict = _as_dict(prompts[i] if i < len(prompts) else {})
|
||||
addi_info = prompt_dict.get("additional_information") or {}
|
||||
mm_kwargs = prompt_dict.get("mm_processor_kwargs") or {}
|
||||
|
||||
# Image size: prefer mm_processor_kwargs target_h/target_w (set by the serving
|
||||
# layer), fall back to additional_information, then a 1024 default.
|
||||
image_height = _coerce_dim(
|
||||
mm_kwargs.get("target_h"),
|
||||
_coerce_dim((addi_info.get("image_height") or [None])[0], 1024),
|
||||
)
|
||||
image_width = _coerce_dim(
|
||||
mm_kwargs.get("target_w"),
|
||||
_coerce_dim((addi_info.get("image_width") or [None])[0], 1024),
|
||||
)
|
||||
|
||||
# Sampling knobs arrive on the DiT stage via extra_body -> extra_args; these are
|
||||
# defensive fallbacks (defaults mirror the former bespoke script's argparse).
|
||||
text_guidance_scale = (addi_info.get("text_guidance_scale") or [9.0])[0]
|
||||
cfg_range = addi_info.get("cfg_range") or [0.0, 1.0]
|
||||
num_inference_steps = (addi_info.get("num_inference_steps") or [50])[0]
|
||||
|
||||
prompt_token_ids = ar_output.prompt_token_ids
|
||||
# exclude the last token because it has no corresponding hidden state
|
||||
@@ -52,36 +86,16 @@ def ar2dit(
|
||||
f"Hidden states length mismatch: expected {len(prompt_token_ids) + len(gen_token_ids)}, got {hidden_total}"
|
||||
)
|
||||
|
||||
mask_device = full_hidden_states.device
|
||||
full_token_ids_t = torch.tensor(full_token_ids, dtype=torch.long, device=mask_device)
|
||||
attention_mask = torch.ones_like(full_token_ids_t, dtype=torch.bool)
|
||||
|
||||
pos = torch.arange(full_token_ids_t.shape[0], device=mask_device)
|
||||
answer_start_index = len(prompt_token_ids)
|
||||
questions_mask = pos < answer_start_index
|
||||
answers_mask = ~questions_mask
|
||||
|
||||
gen_token_mask = full_token_ids_t >= gen_vocab_start_index
|
||||
|
||||
visual_token_mask = torch.isin(
|
||||
full_token_ids_t,
|
||||
torch.tensor(visual_ids, dtype=torch.long, device=mask_device),
|
||||
)
|
||||
|
||||
text_condition_token_mask = questions_mask & ~(visual_token_mask | gen_token_mask) & attention_mask
|
||||
image_condition_token_mask = answers_mask & gen_token_mask & attention_mask
|
||||
|
||||
text_condition = full_hidden_states[text_condition_token_mask]
|
||||
image_condition = full_hidden_states[image_condition_token_mask]
|
||||
|
||||
text_prompt_embeds = text_condition.to(dtype=torch.float32).contiguous()
|
||||
image_prompt_embeds = image_condition.to(dtype=torch.float32).contiguous()
|
||||
|
||||
# The text/image condition split is performed in the DiT pipeline, which sources
|
||||
# the distinguishing token ids (gen_vocab_start_index, vision placeholder ids)
|
||||
# from the model config. Pass through the raw AR hidden states + token ids and
|
||||
# the question/answer boundary so the pipeline can reconstruct the masks.
|
||||
additional_information = {
|
||||
"text_prompt_embeds": text_prompt_embeds,
|
||||
"text_prompt_embeds_shape": list(text_prompt_embeds.shape),
|
||||
"image_prompt_embeds": image_prompt_embeds,
|
||||
"image_prompt_embeds_shape": list(image_prompt_embeds.shape),
|
||||
# float32 so the tensor crosses the stage boundary (the serializer uses
|
||||
# numpy, which has no bf16); the DiT re-casts to the model dtype.
|
||||
"full_hidden_states": full_hidden_states.float().contiguous(),
|
||||
"full_token_ids": full_token_ids,
|
||||
"answer_start_index": [len(prompt_token_ids)],
|
||||
"image_height": [int(image_height)],
|
||||
"image_width": [int(image_width)],
|
||||
"text_guidance_scale": [float(text_guidance_scale)],
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# AR image-grid patch size (pixels per visual token). Mirrors the constant the
|
||||
# bespoke MammothModa2 example used to convert image dimensions -> AR grid dims.
|
||||
_PATCH_SIZE = 16
|
||||
|
||||
_AR_SYSTEM_PROMPT = "You are a helpful image generator."
|
||||
|
||||
|
||||
def build_text_to_image_prompt(
|
||||
prompt: str,
|
||||
negative_prompt: str | None,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the MammothModa2 AR-stage prompt for text-to-image generation.
|
||||
|
||||
Reproduces the prompt string and the structural ``additional_information``
|
||||
that the former bespoke example (``run_mammothmoda2_t2i.py``) constructed,
|
||||
deriving the AR image grid from ``height`` / ``width``.
|
||||
|
||||
Model-specific sampling knobs (``text_guidance_scale``, ``cfg_range``,
|
||||
``num_inference_steps``) flow separately via ``extra_body`` -> ``extra_args``.
|
||||
Config-derived token ids (``eol_token_id``, ``visual_token_start_id``,
|
||||
``visual_token_end_id``, ``visual_ids``) are sourced inside the AR stage
|
||||
rather than passed by the caller -- see the ar2dit stage input processor.
|
||||
|
||||
MammothModa2 t2i uses classifier-free guidance via ``text_guidance_scale``
|
||||
and has no explicit negative-prompt path, so ``negative_prompt`` is accepted
|
||||
for signature compatibility but not injected.
|
||||
"""
|
||||
h = height or 1024
|
||||
w = width or 1024
|
||||
ar_height = h // _PATCH_SIZE
|
||||
ar_width = w // _PATCH_SIZE
|
||||
|
||||
return {
|
||||
"prompt": (
|
||||
f"<|im_start|>system\n{_AR_SYSTEM_PROMPT}<|im_end|>\n"
|
||||
f"<|im_start|>user\n{prompt}<|im_end|>\n"
|
||||
"<|im_start|>assistant\n"
|
||||
f"<|image start|>{ar_width}*{ar_height}<|image token|>"
|
||||
),
|
||||
"additional_information": {
|
||||
"omni_task": ["t2i"],
|
||||
"ar_width": [ar_width],
|
||||
"ar_height": [ar_height],
|
||||
"image_height": [h],
|
||||
"image_width": [w],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
MAMMOTHMODA2_PREVIEW_EXTRA_BODY_PARAMS = frozenset(
|
||||
{
|
||||
"text_guidance_scale",
|
||||
"cfg_range",
|
||||
# MammothModa2's DiT stage consumes inputs via the kwargs interface rather
|
||||
# than OmniDiffusionRequest, so the standard --num-inference-steps flag does
|
||||
# not reach it; it is routed through extra_body like the CFG knobs.
|
||||
"num_inference_steps",
|
||||
}
|
||||
)
|
||||
MAMMOTHMODA2_PREVIEW_EXTRA_OUTPUT_PARAMS = frozenset()
|
||||
MAMMOTHMODA2_PREVIEW_INIT_EXTRA_ARGS_FOR_NON_DIFFUSION_STAGES = True
|
||||
@@ -34,6 +34,14 @@ from vllm_omni.model_extras.magi_human import (
|
||||
MAGI_HUMAN_EXTRA_BODY_PARAMS,
|
||||
MAGI_HUMAN_EXTRA_OUTPUT_PARAMS,
|
||||
)
|
||||
from vllm_omni.model_extras.mammothmodal2_preview import (
|
||||
MAMMOTHMODA2_PREVIEW_EXTRA_BODY_PARAMS,
|
||||
MAMMOTHMODA2_PREVIEW_EXTRA_OUTPUT_PARAMS,
|
||||
MAMMOTHMODA2_PREVIEW_INIT_EXTRA_ARGS_FOR_NON_DIFFUSION_STAGES,
|
||||
)
|
||||
from vllm_omni.model_extras.mammothmodal2_preview import (
|
||||
build_text_to_image_prompt as build_mammothmoda2_text_to_image_prompt,
|
||||
)
|
||||
from vllm_omni.model_extras.sensenova_u1 import (
|
||||
SENSENOVA_U1_EXTRA_BODY_PARAMS,
|
||||
SENSENOVA_U1_EXTRA_OUTPUT_PARAMS,
|
||||
@@ -143,6 +151,12 @@ _EXTRA_SPECS: dict[str, dict[str, Any]] = {
|
||||
"extra_output_params": VACE_EXTRA_OUTPUT_PARAMS,
|
||||
"image_to_video_prompt_builder": build_vace_image_to_video_prompt,
|
||||
},
|
||||
"MammothModa2DiTPipeline": {
|
||||
"extra_body_params": MAMMOTHMODA2_PREVIEW_EXTRA_BODY_PARAMS,
|
||||
"extra_output_params": MAMMOTHMODA2_PREVIEW_EXTRA_OUTPUT_PARAMS,
|
||||
"init_extra_args_for_non_diffusion_stages": MAMMOTHMODA2_PREVIEW_INIT_EXTRA_ARGS_FOR_NON_DIFFUSION_STAGES,
|
||||
"text_to_image_prompt_builder": build_mammothmoda2_text_to_image_prompt,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user