Initialize QMI pipeline implementation (#2)

* init

Signed-off-by: Isotr0py <mozf@inferact.ai>

* fix

Signed-off-by: Isotr0py <mozf@inferact.ai>

---------

Signed-off-by: Isotr0py <mozf@inferact.ai>
This commit is contained in:
Isotr0py authored and GitHub committed 2026-09-16 15:14:23 +08:00
1 parent a7c295d544
commit 2912672b2e
15 files changed
+4725 -1

No files matched your search

@@ -0,0 +1,147 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import torch
from diffusers.models.autoencoders.vae import DecoderOutput
from vllm.logger import init_logger
from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor import (
DistributedOperator,
DistributedVaeMixin,
GridSpec,
TileTask,
)
from vllm_omni.diffusion.models.qwen_image_21.autoencoder_kl_qwenimage21 import (
AutoencoderKLQwenImage21,
_unpatchify,
)
logger = init_logger(__name__)
class DistributedAutoencoderKLQwenImage21(AutoencoderKLQwenImage21, DistributedVaeMixin):
@classmethod
def from_pretrained(cls, *args: Any, **kwargs: Any):
model = super().from_pretrained(*args, **kwargs)
model.init_distributed()
return model
def tile_split(self, z: torch.Tensor) -> tuple[list[TileTask], GridSpec]:
# mostly copy from AutoencoderKLQwenImage21.tiled_decode
_, _, num_frames, height, width = z.shape
sample_height = height * self.spatial_compression_ratio
sample_width = width * self.spatial_compression_ratio
tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio
tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio
tile_latent_stride_height = self.tile_sample_stride_height // self.spatial_compression_ratio
tile_latent_stride_width = self.tile_sample_stride_width // self.spatial_compression_ratio
tile_sample_stride_height = self.tile_sample_stride_height
tile_sample_stride_width = self.tile_sample_stride_width
if self.config.patch_size is not None:
sample_height = sample_height // self.config.patch_size
sample_width = sample_width // self.config.patch_size
tile_sample_stride_height = tile_sample_stride_height // self.config.patch_size
tile_sample_stride_width = tile_sample_stride_width // self.config.patch_size
blend_height = self.tile_sample_min_height // self.config.patch_size - tile_sample_stride_height
blend_width = self.tile_sample_min_width // self.config.patch_size - tile_sample_stride_width
else:
blend_height = self.tile_sample_min_height - tile_sample_stride_height
blend_width = self.tile_sample_min_width - tile_sample_stride_width
# Split z into overlapping tiles and decode them separately.
# The tiles have an overlap to avoid seams between tiles.
tiletask_list = []
for i in range(0, height, tile_latent_stride_height):
for j in range(0, width, tile_latent_stride_width):
time_list = []
for k in range(num_frames):
tile = z[:, :, k : k + 1, i : i + tile_latent_min_height, j : j + tile_latent_min_width]
time_list.append(tile)
tiletask_list.append(
TileTask(
len(tiletask_list),
(i // tile_latent_stride_height, j // tile_latent_stride_width),
time_list,
workload=time_list[0].shape[3] * time_list[0].shape[4],
)
)
tile_spec = {
"sample_height": sample_height,
"sample_width": sample_width,
"blend_height": blend_height,
"blend_width": blend_width,
"tile_sample_stride_height": tile_sample_stride_height,
"tile_sample_stride_width": tile_sample_stride_width,
}
grid_spec = GridSpec(
split_dims=(3, 4),
grid_shape=(tiletask_list[-1].grid_coord[0] + 1, tiletask_list[-1].grid_coord[1] + 1),
tile_spec=tile_spec,
output_dtype=self.dtype,
)
return tiletask_list, grid_spec
def tile_exec(self, task: TileTask) -> torch.Tensor:
"""Decode a single latent tile into RGB space."""
self.clear_cache()
time = []
for k in range(len(task.tensor)):
self._conv_idx = [0]
tile = self.post_quant_conv(task.tensor[k])
decoded = self.decoder(tile, feat_cache=self._feat_map, feat_idx=self._conv_idx, first_chunk=(k == 0))
time.append(decoded)
result = torch.cat(time, dim=2)
return result
def tile_merge(self, coord_tensor_map: dict[tuple[int, ...], torch.Tensor], grid_spec: GridSpec) -> torch.Tensor:
"""Merge decoded tiles into a full image."""
grid_h, grid_w = grid_spec.grid_shape
self.clear_cache()
result_rows = []
for i in range(grid_h):
result_row = []
for j in range(grid_w):
tile = coord_tensor_map[(i, j)]
if i > 0:
tile = self.blend_v(coord_tensor_map[(i - 1, j)], tile, grid_spec.tile_spec["blend_height"])
if j > 0:
tile = self.blend_h(coord_tensor_map[(i, j - 1)], tile, grid_spec.tile_spec["blend_width"])
result_row.append(
tile[
:,
:,
:,
: grid_spec.tile_spec["tile_sample_stride_height"],
: grid_spec.tile_spec["tile_sample_stride_width"],
]
)
result_rows.append(torch.cat(result_row, dim=-1))
dec = torch.cat(result_rows, dim=3)[
:, :, :, : grid_spec.tile_spec["sample_height"], : grid_spec.tile_spec["sample_width"]
]
if self.config.patch_size is not None:
dec = _unpatchify(dec, patch_size=self.config.patch_size)
dec = torch.clamp(dec, min=-1.0, max=1.0)
return dec
def tiled_decode(self, z: torch.Tensor, return_dict: bool = True):
if not self.is_distributed_enabled():
return super().tiled_decode(z, return_dict=return_dict)
logger.debug("Decode running with distributed executor")
result = self.distributed_executor.execute(
z,
DistributedOperator(split=self.tile_split, exec=self.tile_exec, merge=self.tile_merge),
broadcast_result=True,
)
if not return_dict:
return (result,)
return DecoderOutput(sample=result)
+5
View File
@@ -22,6 +22,11 @@ lora_convert_mapping: dict[str, Callable] = {
"QwenImagePipeline": _convert_non_diffusers_qwen_lora_to_diffusers,
"QwenImageEditPipeline": _convert_non_diffusers_qwen_lora_to_diffusers,
"QwenImageEditPlusPipeline": _convert_non_diffusers_qwen_lora_to_diffusers,
# 2.1's single-stream blocks keep the same leaf names the converter's
# protected n-grams cover (`attn.to_q/to_k/to_v`, `img_mlp`, ...), so the
# 2.0 converter applies. Non-diffusers LoRAs that target the fused `to_qkv`
# projection are not supported (the converter would split it into `to.qkv`).
"QwenImage21Pipeline": _convert_non_diffusers_qwen_lora_to_diffusers,
"Wan22Pipeline": _convert_non_diffusers_wan_lora_to_diffusers,
"Wan22I2VPipeline": _convert_non_diffusers_wan_lora_to_diffusers,
}
+8
View File
@@ -20,6 +20,8 @@ class DiffusionModelMetadata:
QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES = 4
# Qwen-Image 2.1 image-conditioned generation caps condition images at 4.
QWEN_IMAGE_21_MAX_INPUT_IMAGES = 4
# Upstream HunyuanImage-3.0 "Multi-Image Fusion" caps reference images at 3.
HUNYUAN_IMAGE3_MAX_INPUT_IMAGES = 3
# Boogu-Image editing (TI2I) supports a single reference image for now.
@@ -31,6 +33,12 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
supports_multimodal_inputs=True,
max_multimodal_image_inputs=QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES,
),
# Qwen-Image 2.1 handles both text-to-image (no image) and
# image-conditioned requests through the same pipeline class.
"QwenImage21Pipeline": DiffusionModelMetadata(
supports_multimodal_inputs=True,
max_multimodal_image_inputs=QWEN_IMAGE_21_MAX_INPUT_IMAGES,
),
"HunyuanImage3Pipeline": DiffusionModelMetadata(
supports_multimodal_inputs=True,
max_multimodal_image_inputs=HUNYUAN_IMAGE3_MAX_INPUT_IMAGES,
@@ -0,0 +1,23 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Qwen Image 2.1 diffusion model components."""
from vllm_omni.diffusion.models.qwen_image_21.autoencoder_kl_qwenimage21 import (
AutoencoderKLQwenImage21,
)
from vllm_omni.diffusion.models.qwen_image_21.pipeline_qwen_image_21 import (
QwenImage21Pipeline,
get_qwen_image_21_post_process_func,
get_qwen_image_21_pre_process_func,
)
from vllm_omni.diffusion.models.qwen_image_21.qwen_image_21_transformer import (
QwenImage21Transformer2DModel,
)
__all__ = [
"AutoencoderKLQwenImage21",
"QwenImage21Pipeline",
"QwenImage21Transformer2DModel",
"get_qwen_image_21_post_process_func",
"get_qwen_image_21_pre_process_func",
]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,190 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""CFG Parallel Mixin for Qwen-Image 2.1.
Differences from the 2.0 mixin (``qwen_image/cfg_parallel.py``):
- The transformer owns a KV cache for the text/condition-image prefix, so the
denoise loop passes a fresh per-generation ``kv_cache`` and names the CFG
branch (``cache_branch="cond"/"uncond"``) on every forward.
- The joint sequence is ``[condition images, ..., target image]`` — the target
noise prediction is the *tail* of the output, not the head.
"""
import logging
from typing import Any
import torch
from vllm_omni.diffusion.distributed.cfg_parallel import (
CFGParallelMixin,
_get_cfg_world_size_or_one,
_unwrap,
_wrap,
)
from vllm_omni.diffusion.distributed.parallel_state import (
get_cfg_group,
get_classifier_free_guidance_rank,
)
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
logger = logging.getLogger(__name__)
class QwenImage21CFGParallelMixin(CFGParallelMixin, ProgressBarMixin):
"""Base Mixin class for the Qwen-Image 2.1 pipeline providing shared CFG methods."""
def predict_noise_maybe_with_cfg(
self,
do_true_cfg: bool,
true_cfg_scale: float,
positive_kwargs: dict[str, Any],
negative_kwargs: dict[str, Any] | None,
cfg_normalize: bool = False,
output_slice: int | None = None,
kwargs: dict[str, Any] | None = None,
) -> torch.Tensor | tuple[torch.Tensor, ...]:
# The base implementation slices `[:, :output_slice]` per branch, which
# matches the 2.0 condition-last layout. 2.1 concatenates condition
# latents *before* the target, so the target prediction is the tail of
# the joint output. Each branch must be tail-sliced *before* the CFG
# combine: positive and negative prompts tokenize to different lengths,
# so the full joint outputs do not align positionally.
def tail_slice(pred: torch.Tensor | tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
if output_slice is None:
return _wrap(pred)
return tuple(p[:, -output_slice:] for p in _wrap(pred))
if do_true_cfg:
if _get_cfg_world_size_or_one() > 1:
cfg_group = get_cfg_group()
cfg_rank = get_classifier_free_guidance_rank()
branch_kwargs = positive_kwargs if cfg_rank == 0 else negative_kwargs
local_pred = tail_slice(self.predict_noise(**branch_kwargs))
gathered = [cfg_group.all_gather(p, separate_tensors=True) for p in local_pred]
positive_noise_pred = tuple(g[0] for g in gathered)
negative_noise_pred = tuple(g[1] for g in gathered)
else:
positive_noise_pred = tail_slice(self.predict_noise(**positive_kwargs))
negative_noise_pred = tail_slice(self.predict_noise(**negative_kwargs))
return self.combine_cfg_noise(
positive_noise_pred,
negative_noise_pred,
true_cfg_scale,
cfg_normalize,
**({} if kwargs is None else {"kwargs": kwargs}),
)
pred = self.predict_noise(**positive_kwargs)
if output_slice is not None:
pred = _unwrap(tail_slice(pred))
return pred
def diffuse(
self,
prompt_embeds: torch.Tensor,
prompt_embeds_mask: torch.Tensor,
negative_prompt_embeds: torch.Tensor | None,
negative_prompt_embeds_mask: torch.Tensor | None,
img_mask: torch.Tensor,
negative_img_mask: torch.Tensor | None,
latents: torch.Tensor,
image_latents: torch.Tensor | None,
img_shapes: list,
timesteps: torch.Tensor,
do_true_cfg: bool,
true_cfg_scale: float,
attention_kwargs: dict[str, Any] | None = None,
additional_transformer_kwargs: dict[str, Any] | None = None,
) -> torch.Tensor:
"""
Diffusion loop with optional classifier-free guidance.
Args:
prompt_embeds: Positive prompt embeddings
prompt_embeds_mask: Mask for positive prompt
negative_prompt_embeds: Negative prompt embeddings
negative_prompt_embeds_mask: Mask for negative prompt
img_mask: Joint-sequence image-slot mask for the positive branch
(VLM image slots plus one slot per 2x2 group of target tokens)
negative_img_mask: Same for the negative branch
latents: Noise latents to denoise (target image only, packed)
image_latents: Packed condition-image latents, prepended to the
noise latents (default: None for pure text-to-image)
img_shapes: Per-sample list of (frame, height, width) latent-token
shapes, condition images first and the target last
timesteps: Diffusion timesteps
do_true_cfg: Whether to apply CFG
true_cfg_scale: CFG scale factor
attention_kwargs: Passed through to the transformer (attn_path hint)
additional_transformer_kwargs: Extra kwargs for the transformer
Returns:
Denoised latents
"""
# Fresh cache for every generation: the pipeline is a singleton shared
# across requests, so cache state must never leak between them.
cache_enabled = getattr(self.transformer, "causal_condition", False)
kv_cache = [{} for _ in range(len(self.transformer.transformer_blocks))] if cache_enabled else None
self.scheduler.set_begin_index(0)
self.transformer.do_true_cfg = do_true_cfg
additional_transformer_kwargs = additional_transformer_kwargs or {}
with self.progress_bar(total=len(timesteps)) as pbar:
for i, t in enumerate(timesteps):
if self.interrupt:
continue
self._current_timestep = t
# Broadcast timestep to match batch size
timestep = t.expand(latents.shape[0]).to(device=latents.device, dtype=latents.dtype)
# Condition image latents go in front of the noise latents.
latent_model_input = latents
if image_latents is not None:
latent_model_input = torch.cat([image_latents, latents], dim=1)
positive_kwargs = {
"hidden_states": latent_model_input,
"timestep": timestep / 1000,
"encoder_hidden_states_mask": prompt_embeds_mask,
"encoder_hidden_states": prompt_embeds,
"img_shapes": img_shapes,
"img_mask": img_mask,
"attention_kwargs": attention_kwargs,
"kv_cache": kv_cache,
"cache_branch": "cond",
**additional_transformer_kwargs,
}
if do_true_cfg:
negative_kwargs = {
"hidden_states": latent_model_input,
"timestep": timestep / 1000,
"encoder_hidden_states_mask": negative_prompt_embeds_mask,
"encoder_hidden_states": negative_prompt_embeds,
"img_shapes": img_shapes,
"img_mask": negative_img_mask,
"attention_kwargs": attention_kwargs,
"kv_cache": kv_cache,
"cache_branch": "uncond",
**additional_transformer_kwargs,
}
else:
negative_kwargs = None
# Prefill (first step) returns the full joint sequence and
# caches the prefix; decode steps return target tokens only.
# Slicing the target tail is correct for both.
noise_pred = self.predict_noise_maybe_with_cfg(
do_true_cfg,
true_cfg_scale,
positive_kwargs,
negative_kwargs,
cfg_normalize=False,
output_slice=latents.size(1),
)
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
pbar.update()
return latents
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+11
View File
@@ -41,6 +41,11 @@ _DIFFUSION_MODELS = {
"pipeline_qwen_image_layered",
"QwenImageLayeredPipeline",
),
"QwenImage21Pipeline": (
"qwen_image_21",
"pipeline_qwen_image_21",
"QwenImage21Pipeline",
),
"GlmImagePipeline": (
"glm_image",
"pipeline_glm_image",
@@ -378,6 +383,10 @@ _NO_CACHE_ACCELERATION = {
# instead of erroring.
"Pi0Pipeline",
"LingBotWorldCausalDMDPipeline",
# Qwen-Image 2.1's transformer carries its own prefix KV cache (keyed by CFG
# branch) across denoising steps, which conflicts with cache_dit / tea_cache
# step-skipping hooks.
"QwenImage21Pipeline",
}
@@ -550,6 +559,7 @@ _DIFFUSION_POST_PROCESS_FUNCS = {
"QwenImagePipeline": "get_qwen_image_post_process_func",
"QwenImageEditPipeline": "get_qwen_image_edit_post_process_func",
"QwenImageEditPlusPipeline": "get_qwen_image_edit_plus_post_process_func",
"QwenImage21Pipeline": "get_qwen_image_21_post_process_func",
"GlmImagePipeline": "get_glm_image_post_process_func",
"ZImagePipeline": "get_post_process_func",
"OvisImagePipeline": "get_ovis_image_post_process_func",
@@ -629,6 +639,7 @@ _DIFFUSION_PRE_PROCESS_FUNCS = {
"BooguImageTurboPipeline": "get_boogu_image_pre_process_func",
"QwenImageEditPipeline": "get_qwen_image_edit_pre_process_func",
"QwenImageEditPlusPipeline": "get_qwen_image_edit_plus_pre_process_func",
"QwenImage21Pipeline": "get_qwen_image_21_pre_process_func",
"LongCatImageEditPipeline": "get_longcat_image_edit_pre_process_func",
"LongCatVideoAvatarPipeline": "get_longcat_video_avatar_pre_process_func",
"QwenImageLayeredPipeline": "get_qwen_image_layered_pre_process_func",