[New Model] Ming-Image (inclusionAI/Ming-Image-0.1-Design) Support (#8021)
Signed-off-by: Yuanheng <jonathan.zhaoyh@gmail.com>
This commit is contained in:
1 parent
cb5f508212
commit
71125f80ad
31 files changed
+1952
-51
No files matched your search
@@ -1,4 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
# Copyright 2025 The vLLM-Omni team.
|
||||
#
|
||||
# Adapted from Ming repository (inclusionAI/Ming) — the ``get_condition_embeds
|
||||
@@ -65,12 +66,16 @@ class MingConditionEncoder(nn.Module):
|
||||
thinker_hidden_size: int = 4096,
|
||||
device: torch.device | str | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
normalize_output: bool = True,
|
||||
strict_loading: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = image_gen_config
|
||||
self.thinker_hidden_size = thinker_hidden_size
|
||||
self._target_device = torch.device(device) if device is not None else None
|
||||
self._target_dtype = dtype
|
||||
self.normalize_output = normalize_output
|
||||
self.strict_loading = strict_loading
|
||||
|
||||
# Populated lazily by ``load_from_checkpoint`` to keep this module
|
||||
# cheap to construct (useful for dummy-init paths and unit tests).
|
||||
@@ -195,6 +200,8 @@ class MingConditionEncoder(nn.Module):
|
||||
condition path to be meaningful.
|
||||
"""
|
||||
if not mlp_path.exists():
|
||||
if self.strict_loading:
|
||||
raise FileNotFoundError(f"Missing Ming MLP directory: {mlp_path}")
|
||||
logger.warning(
|
||||
"[MingConditionEncoder] mlp/ subfolder missing at %s — proj/norm "
|
||||
"will stay randomly initialized. EXPECT BAD IMAGES until this "
|
||||
@@ -206,6 +213,8 @@ class MingConditionEncoder(nn.Module):
|
||||
try:
|
||||
from safetensors.torch import load_file # type: ignore
|
||||
except ImportError:
|
||||
if self.strict_loading:
|
||||
raise
|
||||
logger.exception("[MingConditionEncoder] safetensors not installed")
|
||||
return
|
||||
|
||||
@@ -213,6 +222,8 @@ class MingConditionEncoder(nn.Module):
|
||||
if not candidates:
|
||||
candidates = sorted(mlp_path.glob("*.bin"))
|
||||
if not candidates:
|
||||
if self.strict_loading:
|
||||
raise FileNotFoundError(f"No Ming MLP weights under {mlp_path}")
|
||||
logger.warning("[MingConditionEncoder] no weight files under %s", mlp_path)
|
||||
return
|
||||
|
||||
@@ -258,6 +269,8 @@ class MingConditionEncoder(nn.Module):
|
||||
ok_ow = _copy(self.proj_out.weight, "proj_out.weight")
|
||||
ok_ob = _copy(self.proj_out.bias, "proj_out.bias")
|
||||
if not (ok_w and ok_b and ok_ow and ok_ob):
|
||||
if self.strict_loading:
|
||||
raise ValueError(f"Ming condition projection weights are incomplete or incompatible under {mlp_path}.")
|
||||
logger.error(
|
||||
"[MingConditionEncoder] proj_in/proj_out NOT fully loaded; diffusion conditioning will be garbage."
|
||||
)
|
||||
@@ -342,7 +355,8 @@ class MingConditionEncoder(nn.Module):
|
||||
# L2 normalize + ×1000 rescale. Ming's ``get_condition_embeds_for_image_gen``
|
||||
# applies F.normalize; ``ZImageModel_withMLP`` then rescales by 1000
|
||||
# when ``text_encoder_norm=True``. We fold both into one place.
|
||||
cap_feats = torch.nn.functional.normalize(cap_feats, dim=-1)
|
||||
if self.normalize_output:
|
||||
cap_feats = torch.nn.functional.normalize(cap_feats, dim=-1)
|
||||
if self.config.text_encoder_norm:
|
||||
cap_feats = cap_feats * 1000.0
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Ming-Image specific diffusion components."""
|
||||
@@ -0,0 +1,37 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Validation for Ming-Image component configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def load_mlp_config(model_path: str | Path) -> dict[str, Any]:
|
||||
path = Path(model_path) / "mlp" / "config.json"
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"Ming-Image checkpoint is missing MLP config: {path}")
|
||||
data = json.loads(path.read_text())
|
||||
required = {
|
||||
"diffusion_c_input_dim",
|
||||
"diffusion_inner_dim",
|
||||
"img_gen_scales",
|
||||
"selected_hidden_states_layers",
|
||||
"use_identity_mlp",
|
||||
"use_learnable_token_condition",
|
||||
"use_vlm_directvlm_condition",
|
||||
}
|
||||
missing = sorted(required - data.keys())
|
||||
if missing:
|
||||
raise ValueError(f"Ming-Image MLP config is missing keys: {missing}")
|
||||
if data["img_gen_scales"] != [16]:
|
||||
raise ValueError(f"Only img_gen_scales=[16] is supported, got {data['img_gen_scales']!r}.")
|
||||
if data["selected_hidden_states_layers"] != [5, 12, 20]:
|
||||
raise ValueError("Ming-Image requires selected hidden layers [5, 12, 20].")
|
||||
if not data["use_identity_mlp"]:
|
||||
raise NotImplementedError("Ming-Image non-identity diffusion MLP is not supported.")
|
||||
if not data["use_learnable_token_condition"] or not data["use_vlm_directvlm_condition"]:
|
||||
raise ValueError("Ming-Image requires both query-token and direct-VLM conditioning.")
|
||||
return data
|
||||
@@ -0,0 +1,88 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Ming-Image query and direct-VLM condition projectors."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from safetensors.torch import load_file
|
||||
|
||||
from vllm_omni.diffusion.models.ming_flash_omni.condition_encoder import MingConditionEncoder
|
||||
from vllm_omni.transformers_utils.configs.ming_flash_omni import MingImageGenConfig
|
||||
|
||||
from .component_config import load_mlp_config
|
||||
|
||||
|
||||
class MingImageConditioning(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
model_path: str | Path,
|
||||
*,
|
||||
device: torch.device | str,
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
model_path = Path(model_path)
|
||||
mlp_config = load_mlp_config(model_path)
|
||||
config = MingImageGenConfig(
|
||||
diffusion_c_input_dim=int(mlp_config["diffusion_c_input_dim"]),
|
||||
thinker_hidden_size=2048,
|
||||
img_gen_scales=list(mlp_config["img_gen_scales"]),
|
||||
text_encoder_norm=bool(mlp_config.get("text_encoder_norm", False)),
|
||||
)
|
||||
self.query_encoder = MingConditionEncoder(
|
||||
config,
|
||||
thinker_hidden_size=2048,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
normalize_output=bool(mlp_config.get("connector_norm", False)),
|
||||
strict_loading=True,
|
||||
)
|
||||
self.query_encoder.load_from_checkpoint(model_path)
|
||||
|
||||
selected_layers = mlp_config["selected_hidden_states_layers"]
|
||||
direct_input_dim = 2048 * len(selected_layers)
|
||||
direct_output_dim = int(mlp_config["diffusion_inner_dim"])
|
||||
self.direct_projector = nn.Sequential(
|
||||
nn.RMSNorm(direct_input_dim, eps=1e-5),
|
||||
nn.Linear(direct_input_dim, direct_output_dim, bias=True),
|
||||
).to(device=device, dtype=dtype)
|
||||
self._load_direct_weights(model_path / "mlp" / "model.safetensors")
|
||||
|
||||
def _load_direct_weights(self, path: Path) -> None:
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"Missing Ming-Image direct projector weights: {path}")
|
||||
state = load_file(str(path))
|
||||
mapping = {
|
||||
"0.weight": "proj_directvlm.0.weight",
|
||||
"1.weight": "proj_directvlm.1.weight",
|
||||
"1.bias": "proj_directvlm.1.bias",
|
||||
}
|
||||
own_state = self.direct_projector.state_dict()
|
||||
projected: dict[str, torch.Tensor] = {}
|
||||
for target, source in mapping.items():
|
||||
if source not in state:
|
||||
raise ValueError(f"Missing Ming-Image MLP weight {source!r}.")
|
||||
if own_state[target].shape != state[source].shape:
|
||||
raise ValueError(
|
||||
f"Ming-Image MLP shape mismatch for {source}: "
|
||||
f"expected {tuple(own_state[target].shape)}, got {tuple(state[source].shape)}."
|
||||
)
|
||||
projected[target] = state[source]
|
||||
self.direct_projector.load_state_dict(projected, strict=True)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
query_hidden_states: torch.Tensor,
|
||||
direct_hidden_states: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return (
|
||||
self.query_encoder(query_hidden_states),
|
||||
self.direct_projector(direct_hidden_states),
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["MingImageConditioning"]
|
||||
@@ -0,0 +1,425 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Diffusion pipeline for Ming-Image Design and Design-Layer checkpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Iterable
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from diffusers.image_processor import VaeImageProcessor
|
||||
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
||||
from PIL import Image
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
from vllm_omni.diffusion.compile import regionally_compile
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_qwenimage import (
|
||||
DistributedAutoencoderKLQwenImage,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
set_forward_context_direct_condition,
|
||||
set_forward_context_ref_latent,
|
||||
)
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch
|
||||
from vllm_omni.diffusion.models.ming_image.condition import MingImageConditioning
|
||||
from vllm_omni.diffusion.models.ming_image.transformer import MingImageTransformer2DModel
|
||||
from vllm_omni.diffusion.models.z_image.pipeline_z_image import ZImagePipeline
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.hf_utils import get_diffusion_model_index
|
||||
from vllm_omni.diffusion.utils.tf_utils import get_transformer_config_kwargs
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DESIGN_PIPELINE = "MingImageDiffusionPipeline"
|
||||
_LAYERED_PIPELINE = "MingImageLayeredDiffusionPipeline"
|
||||
_VENDOR_TRANSFORMER_CLASS = "DiffusionTransformer"
|
||||
_DIFFUSION_REQUIRED_PATTERNS = [
|
||||
"model_index.json",
|
||||
"scheduler/**",
|
||||
"transformer/**",
|
||||
"vae/**",
|
||||
"mlp/**",
|
||||
"connector/**",
|
||||
]
|
||||
|
||||
|
||||
def _validate_variant_config(
|
||||
model_index: dict[str, Any] | None,
|
||||
transformer_config: Any,
|
||||
) -> bool:
|
||||
"""Validate checkpoint-owned variant metadata and return layered mode."""
|
||||
declared_transformer = getattr(transformer_config, "_class_name", None)
|
||||
if declared_transformer != _VENDOR_TRANSFORMER_CLASS:
|
||||
raise ValueError(
|
||||
"Ming-Image transformer/config.json must preserve the vendor "
|
||||
f"_class_name={_VENDOR_TRANSFORMER_CLASS!r}, got {declared_transformer!r}. "
|
||||
"vLLM-Omni loads those weights through MingImageTransformer2DModel."
|
||||
)
|
||||
|
||||
alignment_padding_mode = getattr(transformer_config, "alignment_padding_mode", None)
|
||||
multi_frame_output = getattr(transformer_config, "multi_frame_output", None)
|
||||
variant = (alignment_padding_mode, multi_frame_output)
|
||||
if variant == ("zero_masked", False):
|
||||
is_layer_decomposition = False
|
||||
elif variant == ("learned", True):
|
||||
is_layer_decomposition = True
|
||||
else:
|
||||
raise ValueError(
|
||||
"Ming-Image transformer/config.json must use either "
|
||||
"alignment_padding_mode='zero_masked' with multi_frame_output=False "
|
||||
"or alignment_padding_mode='learned' with multi_frame_output=True; "
|
||||
f"got alignment_padding_mode={alignment_padding_mode!r}, "
|
||||
f"multi_frame_output={multi_frame_output!r}."
|
||||
)
|
||||
|
||||
declared_pipeline = (model_index or {}).get("_class_name")
|
||||
if declared_pipeline is not None:
|
||||
if declared_pipeline not in {_DESIGN_PIPELINE, _LAYERED_PIPELINE}:
|
||||
raise ValueError(
|
||||
"Ming-Image model_index.json must declare "
|
||||
f"{_DESIGN_PIPELINE!r} or {_LAYERED_PIPELINE!r}, got {declared_pipeline!r}."
|
||||
)
|
||||
expected_pipeline = _LAYERED_PIPELINE if is_layer_decomposition else _DESIGN_PIPELINE
|
||||
if declared_pipeline != expected_pipeline:
|
||||
raise ValueError(
|
||||
f"Ming-Image model_index.json declares {declared_pipeline!r}, but "
|
||||
f"transformer/config.json describes {expected_pipeline!r}."
|
||||
)
|
||||
return is_layer_decomposition
|
||||
|
||||
|
||||
class MingImageDiffusionPipeline(ZImagePipeline):
|
||||
"""Ming-Image component adapter around the canonical Z-Image loop."""
|
||||
|
||||
supports_request_batch = False
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["conditioning"]
|
||||
_vae_modules: ClassVar[list[str]] = ["vae"]
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = "") -> None:
|
||||
del prefix
|
||||
nn.Module.__init__(self)
|
||||
|
||||
model_path = od_config.model
|
||||
if not os.path.exists(model_path):
|
||||
model_path = download_weights_from_hf_specific(
|
||||
model_name_or_path=model_path,
|
||||
cache_dir=None,
|
||||
allow_patterns=_DIFFUSION_REQUIRED_PATTERNS,
|
||||
revision=od_config.revision,
|
||||
require_all=True,
|
||||
)
|
||||
local_files_only = os.path.isdir(model_path)
|
||||
dtype = od_config.dtype
|
||||
|
||||
self.od_config = od_config
|
||||
self._execution_device = get_local_device()
|
||||
self.device = self._execution_device
|
||||
model_index = get_diffusion_model_index(model_path, revision=od_config.revision) or {}
|
||||
transformer_config = od_config.tf_model_config
|
||||
self.is_layer_decomposition = _validate_variant_config(
|
||||
model_index,
|
||||
transformer_config,
|
||||
)
|
||||
|
||||
self.default_num_inference_steps = 12
|
||||
self.default_guidance_scale = 2.0 if self.is_layer_decomposition else 1.0
|
||||
self._num_frames_per_prompt = 1
|
||||
self._pending_prompt_embeds: list[torch.Tensor] | None = None
|
||||
self._pending_negative_prompt_embeds: list[torch.Tensor] | None = None
|
||||
self._uses_cudagraph_trees = False
|
||||
|
||||
self.weights_sources = [
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=model_path,
|
||||
subfolder="transformer",
|
||||
revision=od_config.revision,
|
||||
prefix="transformer.",
|
||||
fall_back_to_pt=True,
|
||||
)
|
||||
]
|
||||
subfolders = ["scheduler", "transformer", "vae"]
|
||||
|
||||
self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
|
||||
model_path,
|
||||
subfolder="scheduler",
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
|
||||
self.vae = from_pretrained_with_prefetch(
|
||||
DistributedAutoencoderKLQwenImage.from_pretrained,
|
||||
model_path,
|
||||
subfolder="vae",
|
||||
prefetch_list=subfolders,
|
||||
local_files_only=local_files_only,
|
||||
torch_dtype=dtype,
|
||||
).to(self.device)
|
||||
self.vae.eval()
|
||||
vae_channels = int(getattr(self.vae.config, "input_channels", 3))
|
||||
if vae_channels != 4:
|
||||
raise ValueError(f"Ming-Image requires an RGBA VAE, got input_channels={vae_channels}.")
|
||||
|
||||
transformer_kwargs = get_transformer_config_kwargs(
|
||||
od_config.tf_model_config,
|
||||
MingImageTransformer2DModel,
|
||||
)
|
||||
self.transformer = MingImageTransformer2DModel(
|
||||
quant_config=od_config.quantization_config,
|
||||
**transformer_kwargs,
|
||||
)
|
||||
self.conditioning = MingImageConditioning(
|
||||
model_path,
|
||||
device=self.device,
|
||||
dtype=dtype,
|
||||
)
|
||||
self.text_encoder = None
|
||||
self.tokenizer = None
|
||||
|
||||
self.vae_scale_factor = 2 ** len(self.vae.config.temperal_downsample)
|
||||
self.image_processor = VaeImageProcessor(
|
||||
vae_scale_factor=self.vae_scale_factor * 2,
|
||||
do_convert_rgb=False,
|
||||
)
|
||||
self.setup_diffusion_pipeline_profiler(
|
||||
enable_diffusion_pipeline_profiler=od_config.enable_diffusion_pipeline_profiler
|
||||
)
|
||||
|
||||
def setup_compile(self) -> None:
|
||||
# Keep request preparation, scheduling, and VAE work eager,
|
||||
# while capturing repeated DiT blocks for CUDAGraph Trees replay.
|
||||
if self.od_config.diffusion_compile_granularity != "regional":
|
||||
logger.warning(
|
||||
"Ming-Image CUDA Graph uses regional DiT compilation; diffusion_compile_granularity=%r is ignored.",
|
||||
self.od_config.diffusion_compile_granularity,
|
||||
)
|
||||
self.transformer = regionally_compile(
|
||||
self.transformer,
|
||||
mode="reduce-overhead",
|
||||
fullgraph=True,
|
||||
dynamic=self.od_config.diffusion_compile_dynamic,
|
||||
)
|
||||
self._uses_cudagraph_trees = True
|
||||
|
||||
def encode_prompt(self, *args, **kwargs):
|
||||
del args, kwargs
|
||||
if self._pending_prompt_embeds is None or self._pending_negative_prompt_embeds is None:
|
||||
raise RuntimeError("Ming-Image conditioning is only available during forward.")
|
||||
return self._pending_prompt_embeds, self._pending_negative_prompt_embeds
|
||||
|
||||
def prepare_latents(self, batch_size, *args, **kwargs):
|
||||
frames = self._num_frames_per_prompt
|
||||
flat = super().prepare_latents(batch_size * frames, *args, **kwargs)
|
||||
return torch.stack(flat.chunk(frames, dim=0), dim=2)
|
||||
|
||||
def _encode_reference(
|
||||
self,
|
||||
reference: Any | None,
|
||||
height: int,
|
||||
width: int,
|
||||
) -> torch.Tensor | None:
|
||||
if reference is None:
|
||||
return None
|
||||
if isinstance(reference, list):
|
||||
if len(reference) != 1:
|
||||
raise ValueError("Ming-Image currently accepts exactly one reference image.")
|
||||
reference = reference[0]
|
||||
if isinstance(reference, Image.Image):
|
||||
reference = reference.convert("RGBA")
|
||||
if not isinstance(reference, torch.Tensor):
|
||||
reference = self.image_processor.preprocess(reference, height=height, width=width)
|
||||
if reference.ndim != 4 or reference.shape[1] != 4:
|
||||
raise ValueError("Ming-Image reference must be a batched RGBA tensor or an RGBA-compatible image.")
|
||||
reference = reference.to(device=self.device, dtype=self.vae.dtype).unsqueeze(2)
|
||||
latent = self.vae.encode(reference).latent_dist.mode()
|
||||
return (latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
||||
|
||||
@staticmethod
|
||||
def _get_prompt_extra(req: DiffusionRequestBatch) -> dict[str, Any]:
|
||||
if not req.prompts:
|
||||
return {}
|
||||
prompt = req.prompts[0]
|
||||
if isinstance(prompt, dict):
|
||||
return dict(prompt.get("extra") or {})
|
||||
if hasattr(prompt, "_asdict"):
|
||||
return dict(prompt._asdict().get("extra") or {})
|
||||
return {}
|
||||
|
||||
def _configure_output_frames(
|
||||
self,
|
||||
*,
|
||||
reference: Any | None,
|
||||
num_layers: int,
|
||||
is_dummy_run: bool,
|
||||
) -> None:
|
||||
if num_layers < 1:
|
||||
raise ValueError("num_layers must be at least 1.")
|
||||
if self.is_layer_decomposition:
|
||||
if reference is None and not is_dummy_run:
|
||||
raise ValueError("Ming-Image Design-Layer requires a reference image.")
|
||||
self._num_frames_per_prompt = num_layers + 1
|
||||
return
|
||||
if num_layers != 1:
|
||||
raise ValueError("Ming-Image Design supports exactly one output frame.")
|
||||
self._num_frames_per_prompt = 1
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, req: DiffusionRequestBatch) -> DiffusionOutput:
|
||||
sampling = req.sampling_params
|
||||
if sampling.num_outputs_per_prompt != 1:
|
||||
# TODO(yuanheng-zhao): enable after supporting batching
|
||||
raise ValueError(
|
||||
f"Ming-Image currently supports num_outputs_per_prompt=1 only, got {sampling.num_outputs_per_prompt}."
|
||||
)
|
||||
|
||||
extra = self._get_prompt_extra(req)
|
||||
extra_args = sampling.extra_args or {}
|
||||
|
||||
is_dummy_run = req.is_dummy_run()
|
||||
query_hidden = extra.get("query_hidden_states")
|
||||
direct_hidden = extra.get("direct_hidden_states")
|
||||
if query_hidden is None or direct_hidden is None:
|
||||
if not is_dummy_run:
|
||||
raise ValueError("Ming-Image requests require query and direct conditions.")
|
||||
logger.warning("Ming-Image conditions are absent during warmup; using zero tensors.")
|
||||
query_hidden = torch.zeros((256, 2048), device=self.device, dtype=self.od_config.dtype)
|
||||
direct_hidden = torch.zeros((1, 6144), device=self.device, dtype=self.od_config.dtype)
|
||||
if not isinstance(query_hidden, torch.Tensor) or not isinstance(direct_hidden, torch.Tensor):
|
||||
raise TypeError("Ming-Image query and direct conditions must be tensors.")
|
||||
if query_hidden.ndim == 2:
|
||||
query_hidden = query_hidden.unsqueeze(0)
|
||||
if direct_hidden.ndim == 2:
|
||||
direct_hidden = direct_hidden.unsqueeze(0)
|
||||
query_hidden = query_hidden.to(device=self.device, dtype=self.od_config.dtype)
|
||||
direct_hidden = direct_hidden.to(device=self.device, dtype=self.od_config.dtype)
|
||||
cap_feats, direct_condition = self.conditioning(query_hidden, direct_hidden)
|
||||
|
||||
reference = extra.get("reference_image")
|
||||
num_layers = int(extra_args.get("num_layers", extra.get("num_layers", 1)))
|
||||
self._configure_output_frames(
|
||||
reference=reference,
|
||||
num_layers=num_layers,
|
||||
is_dummy_run=is_dummy_run,
|
||||
)
|
||||
|
||||
height = int(extra_args.get("height") or sampling.height or 1024)
|
||||
width = int(extra_args.get("width") or sampling.width or 1024)
|
||||
steps = int(extra_args.get("steps") or sampling.num_inference_steps or self.default_num_inference_steps)
|
||||
cfg = float(
|
||||
extra_args["cfg"]
|
||||
if extra_args.get("cfg") is not None
|
||||
else sampling.guidance_scale
|
||||
if sampling.guidance_scale is not None
|
||||
else self.default_guidance_scale
|
||||
)
|
||||
seed = extra_args.get("seed", sampling.seed)
|
||||
generator = (
|
||||
torch.Generator(device=self.device).manual_seed(int(seed)) if seed is not None else sampling.generator
|
||||
)
|
||||
|
||||
ref_latent = self._encode_reference(reference, height, width)
|
||||
positive = [item for item in cap_feats]
|
||||
negative = [torch.zeros_like(item) for item in positive]
|
||||
self._pending_prompt_embeds = positive
|
||||
self._pending_negative_prompt_embeds = negative
|
||||
|
||||
apply_cfg = cfg > 0
|
||||
context_direct = (
|
||||
torch.cat([direct_condition, torch.zeros_like(direct_condition)], dim=0) if apply_cfg else direct_condition
|
||||
)
|
||||
context_ref = ref_latent
|
||||
if apply_cfg and context_ref is not None:
|
||||
context_ref = context_ref.repeat(2, 1, 1, 1, 1)
|
||||
|
||||
inner_sampling = OmniDiffusionSamplingParams(
|
||||
height=height,
|
||||
width=width,
|
||||
num_inference_steps=steps,
|
||||
guidance_scale=cfg,
|
||||
generator=generator,
|
||||
output_type="latent",
|
||||
)
|
||||
inner_req = DiffusionRequestBatch(
|
||||
requests=[
|
||||
OmniDiffusionRequest(
|
||||
prompt={"prompt": ""},
|
||||
sampling_params=inner_sampling,
|
||||
request_id=req.request_id or "ming-image",
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
set_forward_context_ref_latent(context_ref)
|
||||
set_forward_context_direct_condition(context_direct)
|
||||
try:
|
||||
latent_output = super().forward(inner_req)
|
||||
if not isinstance(latent_output.output, torch.Tensor):
|
||||
raise TypeError("Ming-Image denoising must return latent tensors.")
|
||||
image = self._decode_latent_frames(latent_output.output)
|
||||
return DiffusionOutput(
|
||||
output=image,
|
||||
stage_durations=latent_output.stage_durations,
|
||||
)
|
||||
finally:
|
||||
set_forward_context_ref_latent(None)
|
||||
set_forward_context_direct_condition(None)
|
||||
self._pending_prompt_embeds = None
|
||||
self._pending_negative_prompt_embeds = None
|
||||
self._num_frames_per_prompt = 1
|
||||
|
||||
@staticmethod
|
||||
def _flatten_latent_frames(latents: torch.Tensor) -> torch.Tensor:
|
||||
if latents.ndim == 4:
|
||||
return latents
|
||||
if latents.ndim != 5:
|
||||
raise ValueError(f"Expected 4D or 5D Ming-Image latents, got {tuple(latents.shape)}")
|
||||
batch, channels, frames, height, width = latents.shape
|
||||
return latents.permute(2, 0, 1, 3, 4).reshape(
|
||||
frames * batch,
|
||||
channels,
|
||||
height,
|
||||
width,
|
||||
)
|
||||
|
||||
def _decode_latent_frames(self, latents: torch.Tensor) -> torch.Tensor:
|
||||
latents = self._flatten_latent_frames(latents).to(self.vae.dtype).unsqueeze(2)
|
||||
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
||||
image = self.vae.decode(latents, return_dict=False)[0]
|
||||
if image.ndim == 5:
|
||||
if image.shape[2] != 1:
|
||||
raise ValueError(
|
||||
f"Ming-Image VAE returned multiple decoded frames for a single latent frame: {tuple(image.shape)}"
|
||||
)
|
||||
image = image.squeeze(2)
|
||||
return image
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loaded = AutoWeightsLoader(self).load_weights(weights)
|
||||
loaded |= {f"vae.{name}" for name, _ in self.vae.named_parameters()}
|
||||
loaded |= {f"conditioning.{name}" for name, _ in self.conditioning.named_parameters()}
|
||||
return loaded
|
||||
|
||||
|
||||
def get_ming_image_post_process_func(od_config: OmniDiffusionConfig):
|
||||
del od_config
|
||||
image_processor = VaeImageProcessor(vae_scale_factor=16, do_convert_rgb=False)
|
||||
|
||||
def post_process(images: torch.Tensor):
|
||||
if images.ndim == 5:
|
||||
images = images.permute(0, 2, 1, 3, 4).flatten(0, 1)
|
||||
return image_processor.postprocess(images.float())
|
||||
|
||||
return post_process
|
||||
|
||||
|
||||
__all__ = ["MingImageDiffusionPipeline", "get_ming_image_post_process_func"]
|
||||
@@ -0,0 +1,52 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Ming-Image adapter for the shared Z-Image transformer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
from vllm_omni.diffusion.models.z_image.z_image_transformer import ZImageTransformer2DModel
|
||||
|
||||
|
||||
class MingImageTransformer2DModel(ZImageTransformer2DModel):
|
||||
"""Runtime adapter for vendor DiffusionTransformer checkpoints.
|
||||
|
||||
This adapter reuses the shared Z-Image DiT and injects Ming-specific request conditions.
|
||||
"""
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: list[torch.Tensor],
|
||||
t,
|
||||
cap_feats: list[torch.Tensor],
|
||||
patch_size=2,
|
||||
f_patch_size=1,
|
||||
):
|
||||
generated_frames = [item.shape[1] for item in x]
|
||||
ref_x = None
|
||||
cap_feats_2 = None
|
||||
if is_forward_context_available():
|
||||
context = get_forward_context()
|
||||
if context.ref_latent is not None:
|
||||
ref_x = [item.to(device=x[0].device, dtype=x[0].dtype) for item in context.ref_latent.unbind(dim=0)]
|
||||
if context.direct_condition is not None:
|
||||
cap_feats_2 = [
|
||||
item.to(device=x[0].device, dtype=x[0].dtype) for item in context.direct_condition.unbind(dim=0)
|
||||
]
|
||||
|
||||
output, metadata = super().forward(
|
||||
x,
|
||||
t,
|
||||
cap_feats,
|
||||
patch_size=patch_size,
|
||||
f_patch_size=f_patch_size,
|
||||
ref_x=ref_x,
|
||||
cap_feats_2=cap_feats_2,
|
||||
)
|
||||
output = [item[:, :frames] for item, frames in zip(output, generated_frames)]
|
||||
return output, metadata
|
||||
|
||||
|
||||
__all__ = ["MingImageTransformer2DModel"]
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
# Copyright 2025 Alibaba Z-Image Team and The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
@@ -584,7 +584,8 @@ class ZImagePipeline(nn.Module, DiffusionPipelineProfilerMixin, SupportsComponen
|
||||
|
||||
# 5. Prepare timesteps
|
||||
if image is None:
|
||||
image_seq_len = (latents.shape[2] // 2) * (latents.shape[3] // 2)
|
||||
# for both [B, C, H, W] and multi-layer/frame [B, C, F, H, W]
|
||||
image_seq_len = (latents.shape[-2] // 2) * (latents.shape[-1] // 2)
|
||||
mu = calculate_shift(
|
||||
image_seq_len,
|
||||
self.scheduler.config.get("base_image_seq_len", 256),
|
||||
@@ -643,7 +644,8 @@ class ZImagePipeline(nn.Module, DiffusionPipelineProfilerMixin, SupportsComponen
|
||||
latents_typed = latents.to(self.od_config.dtype)
|
||||
|
||||
if apply_cfg:
|
||||
latent_model_input = latents_typed.repeat(2, 1, 1, 1)
|
||||
repeat_dims = (2,) + (1,) * (latents_typed.ndim - 1)
|
||||
latent_model_input = latents_typed.repeat(*repeat_dims)
|
||||
prompt_embeds_model_input = prompt_embeds + negative_prompt_embeds
|
||||
timestep_model_input = timestep.repeat(2)
|
||||
else:
|
||||
@@ -651,9 +653,13 @@ class ZImagePipeline(nn.Module, DiffusionPipelineProfilerMixin, SupportsComponen
|
||||
prompt_embeds_model_input = prompt_embeds
|
||||
timestep_model_input = timestep
|
||||
|
||||
latent_model_input = latent_model_input.unsqueeze(2)
|
||||
if latent_model_input.ndim == 4:
|
||||
latent_model_input = latent_model_input.unsqueeze(2)
|
||||
latent_model_input_list = list(latent_model_input.unbind(dim=0))
|
||||
|
||||
if getattr(self, "_uses_cudagraph_trees", False):
|
||||
# check Ming-Image
|
||||
torch.compiler.cudagraph_mark_step_begin()
|
||||
model_out_list = self.transformer(
|
||||
latent_model_input_list,
|
||||
timestep_model_input,
|
||||
@@ -690,7 +696,8 @@ class ZImagePipeline(nn.Module, DiffusionPipelineProfilerMixin, SupportsComponen
|
||||
else:
|
||||
noise_pred = torch.stack([t.float() for t in model_out_list], dim=0)
|
||||
|
||||
noise_pred = noise_pred.squeeze(2)
|
||||
if latents.ndim == 4:
|
||||
noise_pred = noise_pred.squeeze(2)
|
||||
noise_pred = -noise_pred
|
||||
|
||||
# compute the previous noisy sample x_t -> x_t-1
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
# _sp_plan definition adapted from HuggingFace diffusers library (_cp_plan)
|
||||
|
||||
# Copyright 2025 Alibaba Z-Image Team and The HuggingFace Team. All rights reserved.
|
||||
@@ -56,6 +56,8 @@ from vllm_omni.model_executor.layers.timestep_embedding import timestep_embeddin
|
||||
ADALN_EMBED_DIM = 256
|
||||
SEQ_MULTI_OF = 32
|
||||
|
||||
LEARNED_PADDING = "learned"
|
||||
ZERO_MASKED_PADDING = "zero_masked"
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -81,6 +83,8 @@ class UnifiedPrepare(nn.Module):
|
||||
cap_sin: torch.Tensor,
|
||||
x_item_seqlens: list[int],
|
||||
cap_item_seqlens: list[int],
|
||||
x_attn_mask: torch.Tensor,
|
||||
cap_attn_mask: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Combine x and cap tensors into unified sequences.
|
||||
|
||||
@@ -110,8 +114,9 @@ class UnifiedPrepare(nn.Module):
|
||||
unified_cos = pad_sequence(unified_cos, batch_first=True, padding_value=0.0)
|
||||
unified_sin = pad_sequence(unified_sin, batch_first=True, padding_value=0.0)
|
||||
unified_attn_mask = torch.zeros((bsz, unified_max_item_seqlen), dtype=torch.bool, device=device)
|
||||
for i, seq_len in enumerate(unified_item_seqlens):
|
||||
unified_attn_mask[i, :seq_len] = 1
|
||||
for i, (x_len, cap_len) in enumerate(zip(x_item_seqlens, cap_item_seqlens)):
|
||||
unified_attn_mask[i, :x_len] = x_attn_mask[i, :x_len]
|
||||
unified_attn_mask[i, x_len : x_len + cap_len] = cap_attn_mask[i, :cap_len]
|
||||
|
||||
return unified, unified_cos, unified_sin, unified_attn_mask
|
||||
|
||||
@@ -671,6 +676,8 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
axes_dims=[32, 48, 48],
|
||||
axes_lens=[1024, 512, 512],
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
alignment_padding_mode: str = LEARNED_PADDING,
|
||||
multi_frame_output: bool = True,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
# NOTE: `DiffusersPipelineLoader.load_model()` initializes this module
|
||||
@@ -685,6 +692,12 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
self.dim = dim
|
||||
self.n_heads = n_heads
|
||||
|
||||
if alignment_padding_mode not in {LEARNED_PADDING, ZERO_MASKED_PADDING}:
|
||||
raise ValueError(f"Unsupported Z-Image alignment padding mode: {alignment_padding_mode!r}")
|
||||
if type(multi_frame_output) is not bool:
|
||||
raise ValueError("multi_frame_output must be boolean.")
|
||||
self.alignment_padding_mode = alignment_padding_mode
|
||||
self.multi_frame_output = multi_frame_output
|
||||
self.rope_theta = rope_theta
|
||||
self.t_scale = t_scale
|
||||
self.gradient_checkpointing = False
|
||||
@@ -780,8 +793,12 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
),
|
||||
)
|
||||
|
||||
self.x_pad_token = nn.Parameter(torch.empty((1, dim)))
|
||||
self.cap_pad_token = nn.Parameter(torch.empty((1, dim)))
|
||||
if alignment_padding_mode == LEARNED_PADDING:
|
||||
self.x_pad_token = nn.Parameter(torch.empty((1, dim)))
|
||||
self.cap_pad_token = nn.Parameter(torch.empty((1, dim)))
|
||||
else:
|
||||
self.register_parameter("x_pad_token", None)
|
||||
self.register_parameter("cap_pad_token", None)
|
||||
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
@@ -823,6 +840,8 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
.permute(6, 0, 3, 1, 4, 2, 5)
|
||||
.reshape(self.out_channels, F, H, W)
|
||||
)
|
||||
if not self.multi_frame_output:
|
||||
x[i] = x[i][:, :1]
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
@@ -840,6 +859,8 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
all_cap_feats: list[torch.Tensor],
|
||||
patch_size: int,
|
||||
f_patch_size: int,
|
||||
all_image_ref: list[torch.Tensor | None] | None = None,
|
||||
all_cap_feats_2: list[torch.Tensor | None] | None = None,
|
||||
):
|
||||
pH = pW = patch_size
|
||||
pF = f_patch_size
|
||||
@@ -852,10 +873,16 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
all_cap_pos_ids = []
|
||||
all_cap_pad_mask = []
|
||||
all_cap_feats_out = []
|
||||
all_cap_feats_2_out = []
|
||||
|
||||
for i, (image, cap_feat) in enumerate(zip(all_image, all_cap_feats)):
|
||||
if all_image_ref is None:
|
||||
all_image_ref = [None] * len(all_image)
|
||||
if all_cap_feats_2 is None:
|
||||
all_cap_feats_2 = [None] * len(all_image)
|
||||
|
||||
for image, cap_feat, cap_feat_2, image_ref in zip(all_image, all_cap_feats, all_cap_feats_2, all_image_ref):
|
||||
### Process Caption
|
||||
cap_ori_len = len(cap_feat)
|
||||
cap_ori_len = len(cap_feat) + (len(cap_feat_2) if cap_feat_2 is not None else 0)
|
||||
cap_padding_len = (-cap_ori_len) % SEQ_MULTI_OF
|
||||
# padded position ids
|
||||
cap_padded_pos_ids = self.create_coordinate_grid(
|
||||
@@ -875,13 +902,17 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
)
|
||||
)
|
||||
# padded feature
|
||||
cap_padded_feat = torch.cat(
|
||||
[cap_feat, cap_feat[-1:].repeat(cap_padding_len, 1)],
|
||||
dim=0,
|
||||
)
|
||||
all_cap_feats_out.append(cap_padded_feat)
|
||||
if cap_feat_2 is None:
|
||||
all_cap_feats_out.append(torch.cat([cap_feat, cap_feat[-1:].repeat(cap_padding_len, 1)], dim=0))
|
||||
else:
|
||||
all_cap_feats_out.append(cap_feat)
|
||||
all_cap_feats_2_out.append(
|
||||
torch.cat([cap_feat_2, torch.zeros_like(cap_feat_2[-1:]).repeat(cap_padding_len, 1)])
|
||||
)
|
||||
|
||||
### Process Image
|
||||
if image_ref is not None:
|
||||
image = torch.cat([image, image_ref], dim=1)
|
||||
C, F, H, W = image.size()
|
||||
all_image_size.append((F, H, W))
|
||||
F_tokens, H_tokens, W_tokens = F // pF, H // pH, W // pW
|
||||
@@ -931,6 +962,7 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
all_cap_pos_ids,
|
||||
all_image_pad_mask,
|
||||
all_cap_pad_mask,
|
||||
all_cap_feats_2_out,
|
||||
)
|
||||
|
||||
def forward(
|
||||
@@ -940,6 +972,8 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
cap_feats: list[torch.Tensor],
|
||||
patch_size=2,
|
||||
f_patch_size=1,
|
||||
ref_x: list[torch.Tensor | None] | None = None,
|
||||
cap_feats_2: list[torch.Tensor] | None = None,
|
||||
):
|
||||
assert patch_size in self.all_patch_size
|
||||
assert f_patch_size in self.all_f_patch_size
|
||||
@@ -957,7 +991,8 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
cap_pos_ids,
|
||||
x_inner_pad_mask,
|
||||
cap_inner_pad_mask,
|
||||
) = self.patchify_and_embed(x, cap_feats, patch_size, f_patch_size)
|
||||
cap_feats_2,
|
||||
) = self.patchify_and_embed(x, cap_feats, patch_size, f_patch_size, ref_x, cap_feats_2)
|
||||
|
||||
# x embed & refine
|
||||
x_item_seqlens = [len(_) for _ in x]
|
||||
@@ -971,9 +1006,14 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
adaln_input = t.type_as(x)
|
||||
# Use torch.where instead of x[mask]= to avoid aten::index_put_/nonzero and cudaStreamSynchronize
|
||||
x_pad_mask = torch.cat(x_inner_pad_mask)
|
||||
x_padding = (
|
||||
self.x_pad_token.expand(x.shape[0], -1)
|
||||
if self.alignment_padding_mode == LEARNED_PADDING
|
||||
else torch.zeros_like(x)
|
||||
)
|
||||
x = torch.where(
|
||||
x_pad_mask.unsqueeze(1).expand_as(x),
|
||||
self.x_pad_token.expand(x.shape[0], -1),
|
||||
x_padding,
|
||||
x,
|
||||
)
|
||||
x = list(x.split(x_item_seqlens, dim=0))
|
||||
@@ -987,22 +1027,36 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
x_attn_mask = torch.zeros((bsz, x_max_item_seqlen), dtype=torch.bool, device=device)
|
||||
for i, seq_len in enumerate(x_item_seqlens):
|
||||
x_attn_mask[i, :seq_len] = 1
|
||||
if self.alignment_padding_mode == ZERO_MASKED_PADDING:
|
||||
x_attn_mask[i, :seq_len].masked_fill_(x_inner_pad_mask[i], False)
|
||||
|
||||
for layer in self.noise_refiner:
|
||||
x = layer(x, x_attn_mask, x_cos, x_sin, adaln_input)
|
||||
|
||||
# cap embed & refine
|
||||
cap_item_seqlens = [len(_) for _ in cap_feats]
|
||||
cap_feats = torch.cat(cap_feats, dim=0)
|
||||
cap_feats = self.cap_embedder(cap_feats)
|
||||
if cap_feats_2:
|
||||
cap_feats = list(cap_feats.split(cap_item_seqlens, dim=0))
|
||||
if len(cap_feats) != len(cap_feats_2):
|
||||
raise ValueError("Primary and direct caption conditions must have equal batch size.")
|
||||
cap_feats = [torch.cat([primary, direct], dim=0) for primary, direct in zip(cap_feats, cap_feats_2)]
|
||||
cap_item_seqlens = [len(item) for item in cap_feats]
|
||||
cap_feats = torch.cat(cap_feats, dim=0)
|
||||
assert all(_ % SEQ_MULTI_OF == 0 for _ in cap_item_seqlens)
|
||||
cap_max_item_seqlen = max(cap_item_seqlens)
|
||||
|
||||
cap_feats = torch.cat(cap_feats, dim=0)
|
||||
cap_feats = self.cap_embedder(cap_feats)
|
||||
# Use torch.where instead of cap_feats[mask]= to avoid aten::index_put_/nonzero and cudaStreamSynchronize
|
||||
cap_pad_mask = torch.cat(cap_inner_pad_mask)
|
||||
cap_padding = (
|
||||
self.cap_pad_token.expand(cap_feats.shape[0], -1)
|
||||
if self.alignment_padding_mode == LEARNED_PADDING
|
||||
else torch.zeros_like(cap_feats)
|
||||
)
|
||||
cap_feats = torch.where(
|
||||
cap_pad_mask.unsqueeze(1).expand_as(cap_feats),
|
||||
self.cap_pad_token.expand(cap_feats.shape[0], -1),
|
||||
cap_padding,
|
||||
cap_feats,
|
||||
)
|
||||
cap_feats = list(cap_feats.split(cap_item_seqlens, dim=0))
|
||||
@@ -1016,6 +1070,8 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
cap_attn_mask = torch.zeros((bsz, cap_max_item_seqlen), dtype=torch.bool, device=device)
|
||||
for i, seq_len in enumerate(cap_item_seqlens):
|
||||
cap_attn_mask[i, :seq_len] = 1
|
||||
if self.alignment_padding_mode == ZERO_MASKED_PADDING:
|
||||
cap_attn_mask[i, :seq_len].masked_fill_(cap_inner_pad_mask[i], False)
|
||||
|
||||
for layer in self.context_refiner:
|
||||
cap_feats = layer(cap_feats, cap_attn_mask, cap_cos, cap_sin)
|
||||
@@ -1023,9 +1079,17 @@ class ZImageTransformer2DModel(CachedTransformer):
|
||||
# Prepare unified tensors via UnifiedPrepare module
|
||||
# This enables _cp_plan to shard outputs via split_output=True
|
||||
unified, unified_cos, unified_sin, unified_attn_mask = self.unified_prepare(
|
||||
x, x_cos, x_sin, cap_feats, cap_cos, cap_sin, x_item_seqlens, cap_item_seqlens
|
||||
x,
|
||||
x_cos,
|
||||
x_sin,
|
||||
cap_feats,
|
||||
cap_cos,
|
||||
cap_sin,
|
||||
x_item_seqlens,
|
||||
cap_item_seqlens,
|
||||
x_attn_mask,
|
||||
cap_attn_mask,
|
||||
)
|
||||
|
||||
# Main transformer blocks
|
||||
for layer in self.layers:
|
||||
unified = layer(unified, unified_attn_mask, unified_cos, unified_sin, adaln_input)
|
||||
|
||||
Reference in new issue
Block a user