Merge branch 'main' into lance-model-support; drop lance.yaml

Resolves conflicts in:
- vllm_omni/diffusion/registry.py: keep both LancePipeline (HEAD)
  and MingImagePipeline (main) entries.
- vllm_omni/diffusion/models/bagel/bagel_transformer.py: take main's
  simpler cfg_batched payload; HEAD referenced undefined locals.

Also strips vllm_omni/deploy/lance.yaml -- Lance is single-stage
diffusion, so its engine knobs (pipeline=lance, enforce_eager,
trust_remote_code, max_num_seqs=1, ...) flow directly to Omni(...)
/ vllm-omni serve instead of through a deploy YAML.
create_default_diffusion builds the stage config from those kwargs.

Touched: examples/offline_inference/lance/{end2end,gradio_demo}.py,
tests/e2e/online_serving/test_lance.py, tests/helpers/stage_config.py.

Signed-off-by: lishunyang12 <lishunyang12@163.com>
This commit is contained in:
lishunyang12 committed 2026-05-31 11:50:21 +00:00
commit c15f51a2f6
419 files changed
+46193 -5592

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -793,13 +793,7 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
cfg_renorm_type=gen_params.cfg_renorm_type,
**generation_input,
cfg_text_packed_position_ids=generation_input_cfg_text["cfg_packed_position_ids"],
cfg_text_packed_query_indexes=generation_input_cfg_text["cfg_packed_query_indexes"],
cfg_text_key_values_lens=generation_input_cfg_text["cfg_key_values_lens"],
cfg_text_packed_key_value_indexes=generation_input_cfg_text["cfg_packed_key_value_indexes"],
cfg_img_packed_position_ids=generation_input_cfg_img["cfg_packed_position_ids"],
cfg_img_packed_query_indexes=generation_input_cfg_img["cfg_packed_query_indexes"],
cfg_img_key_values_lens=generation_input_cfg_img["cfg_key_values_lens"],
cfg_img_packed_key_value_indexes=generation_input_cfg_img["cfg_packed_key_value_indexes"],
return_trajectory_latents=req.sampling_params.return_trajectory_latents,
scheduler=self.scheduler,
scheduler_kwargs=self.scheduler_kwargs,
@@ -1,18 +1,28 @@
import re
from typing import TYPE_CHECKING
import torch
import torch.nn as nn
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm_omni.diffusion.attention.layer import Attention
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
try:
from dreamid_omni.modules.model import WanLayerNorm, WanRMSNorm
from dreamid_omni.modules.model import WanLayerNorm
except ImportError:
raise ImportError("Failed to import from dependency 'dreamid_omni'.")
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.models.dreamid_omni.wan2_2 import WanModel, rope_apply
from vllm_omni.diffusion.models.dreamid_omni.wan2_2 import (
DistributedRMSNorm,
WanModel,
rope_apply,
)
logger = init_logger(__name__)
@@ -128,8 +138,8 @@ class FusedBlock(nn.Module):
def forward(
self,
vid,
audio,
hidden_states,
encoder_hidden_states,
attn: Attention,
vid_e,
vid_seq_lens,
@@ -148,6 +158,8 @@ class FusedBlock(nn.Module):
audio_ref_lengths,
audio_freqs_scaling,
):
vid = hidden_states
audio = encoder_hidden_states
vid_block = self.vid_block
audio_block = self.audio_block
@@ -241,26 +253,36 @@ class FusedBlock(nn.Module):
class FusionModel(nn.Module):
_layerwise_offload_blocks_attrs = ["fused_blocks"]
packed_modules_mapping = {
"to_qkv": ["q", "k", "v"],
}
@staticmethod
def _is_fused_block(name: str, module) -> bool:
return "fused_blocks" in name and name.split(".")[-1].isdigit()
_hsdp_shard_conditions = [_is_fused_block]
def __init__(self, video_config=None, audio_config=None):
def __init__(
self,
video_config=None,
audio_config=None,
*,
quant_config: "QuantizationConfig | None" = None,
):
super().__init__()
has_video = True
has_audio = True
self.device = get_local_device()
if video_config is not None:
self.video_model = WanModel(**video_config)
self.video_model = WanModel(quant_config=quant_config, prefix="video_model", **video_config)
else:
has_video = False
self.video_model = None
logger.warning("No video model is provided!")
if audio_config is not None:
self.audio_model = WanModel(**audio_config)
self.audio_model = WanModel(quant_config=quant_config, prefix="audio_model", **audio_config)
else:
has_audio = False
self.audio_model = None
@@ -270,11 +292,12 @@ class FusionModel(nn.Module):
assert len(self.video_model.blocks) == len(self.audio_model.blocks)
self.num_blocks = len(self.video_model.blocks)
self.inject_cross_attention_kv_projections()
self.inject_cross_attention_kv_projections(quant_config=quant_config)
self.num_heads = self.video_model.num_heads
tp_size = get_tensor_model_parallel_world_size()
self.full_num_heads = self.video_model.num_heads
self.num_heads = self.full_num_heads // tp_size
self.head_dim = self.video_model.dim // self.video_model.num_heads
# Make a single shared instance to pass in at forward time
self.attn = Attention(
num_heads=self.num_heads,
head_size=self.head_dim,
@@ -313,21 +336,42 @@ class FusionModel(nn.Module):
return super().load_state_dict(state_dict, strict=strict, assign=assign)
def inject_cross_attention_kv_projections(self):
for vid_block in self.video_model.blocks:
vid_block.cross_attn.k_fusion = nn.Linear(vid_block.dim, vid_block.dim)
vid_block.cross_attn.v_fusion = nn.Linear(vid_block.dim, vid_block.dim)
vid_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(vid_block.dim, elementwise_affine=True)
vid_block.cross_attn.norm_k_fusion = (
WanRMSNorm(vid_block.dim, eps=1e-6) if vid_block.qk_norm else nn.Identity()
def inject_cross_attention_kv_projections(
self,
quant_config: "QuantizationConfig | None" = None,
):
def _make_kv_proj(dim: int, prefix: str) -> ColumnParallelLinear:
# K/V projections for the cross-modal (a2v / v2a) attention path.
# Inputs are full latents, so we quantize matched to self_attn.
return ColumnParallelLinear(
dim,
dim,
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=prefix,
)
for audio_block in self.audio_model.blocks:
audio_block.cross_attn.k_fusion = nn.Linear(audio_block.dim, audio_block.dim)
audio_block.cross_attn.v_fusion = nn.Linear(audio_block.dim, audio_block.dim)
audio_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(audio_block.dim, elementwise_affine=True)
audio_block.cross_attn.norm_k_fusion = (
WanRMSNorm(audio_block.dim, eps=1e-6) if audio_block.qk_norm else nn.Identity()
tp_size = get_tensor_model_parallel_world_size()
for i, vid_block in enumerate(self.video_model.blocks):
cross = vid_block.cross_attn
block_prefix = f"video_model.blocks.{i}.cross_attn"
cross.k_fusion = _make_kv_proj(vid_block.dim, f"{block_prefix}.k_fusion")
cross.v_fusion = _make_kv_proj(vid_block.dim, f"{block_prefix}.v_fusion")
cross.pre_attn_norm_fusion = WanLayerNorm(vid_block.dim, elementwise_affine=True)
cross.norm_k_fusion = (
DistributedRMSNorm(vid_block.dim // tp_size, eps=1e-6) if vid_block.qk_norm else nn.Identity()
)
for i, audio_block in enumerate(self.audio_model.blocks):
cross = audio_block.cross_attn
block_prefix = f"audio_model.blocks.{i}.cross_attn"
cross.k_fusion = _make_kv_proj(audio_block.dim, f"{block_prefix}.k_fusion")
cross.v_fusion = _make_kv_proj(audio_block.dim, f"{block_prefix}.v_fusion")
cross.pre_attn_norm_fusion = WanLayerNorm(audio_block.dim, elementwise_affine=True)
cross.norm_k_fusion = (
DistributedRMSNorm(audio_block.dim // tp_size, eps=1e-6) if audio_block.qk_norm else nn.Identity()
)
def _detach_blocks_from_backbones(self) -> None:
@@ -13,6 +13,11 @@ from PIL import Image, ImageOps
from torch import nn
from torchvision.transforms import Compose, Normalize
from tqdm import tqdm
from vllm.distributed import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
@@ -124,7 +129,8 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
self.text_encoder = self.text_model.model
# Fusion model — weights are loaded later via load_weights()
self.model = FusionModel(VIDEO_CONFIG, AUDIO_CONFIG)
quant_config = getattr(self.od_config, "quantization_config", None)
self.model = FusionModel(VIDEO_CONFIG, AUDIO_CONFIG, quant_config=quant_config)
self.transformer = self.model
fusion_path = self.od_config.tf_model_config.get("fusion", None)
@@ -236,10 +242,75 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
return ref_vae_latents, ref_audio_lengths
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
prefix = "model."
state_dict = {name[len(prefix) :]: tensor for name, tensor in weights if name.startswith(prefix)}
self.model.load_state_dict(state_dict, strict=True)
return {prefix + k for k in state_dict}
pipeline_prefix = "model."
qkv_stacked_mapping = [
(".self_attn.to_qkv", ".self_attn.q", "q"),
(".self_attn.to_qkv", ".self_attn.k", "k"),
(".self_attn.to_qkv", ".self_attn.v", "v"),
]
params_dict = dict(self.model.named_parameters())
loaded_local: set[str] = set()
tp_size = get_tensor_model_parallel_world_size()
tp_rank = get_tensor_model_parallel_rank() if tp_size > 1 else 0
def _maybe_shard_weight(weight: torch.Tensor, param: torch.Tensor) -> torch.Tensor:
"""Slice a checkpoint tensor to this rank's TP shard when the
param is a TP-local shape but the checkpoint stores the full one.
"""
if tp_size <= 1 or weight.shape == param.shape:
return weight
if weight.ndim == 1 and weight.numel() == param.numel() * tp_size:
return weight.chunk(tp_size, dim=0)[tp_rank]
if weight.ndim == 2:
if weight.shape[0] == param.shape[0] * tp_size:
return weight.chunk(tp_size, dim=0)[tp_rank]
if weight.shape[1] == param.shape[1] * tp_size:
return weight.chunk(tp_size, dim=1)[tp_rank]
return weight
for full_name, loaded_weight in weights:
if not full_name.startswith(pipeline_prefix):
continue
name = full_name[len(pipeline_prefix) :]
# Fused-QKV stacking: route checkpoint's separate
# - ...self_attn.{q,k,v}: weights into the corresponding
# - ...self_attn.to_qkv : via its sharded weight_loader.
stacked_hit = False
for fused_name, raw_name, shard_id in qkv_stacked_mapping:
if raw_name not in name:
continue
stacked = name.replace(raw_name, fused_name)
if stacked not in params_dict:
continue
param = params_dict[stacked]
param.weight_loader(param, loaded_weight, shard_id)
loaded_local.add(stacked)
stacked_hit = True
break
if stacked_hit:
continue
if name not in params_dict:
logger.warning(f"Skipping DreamID-Omni weight {full_name} -- not found in model parameters")
continue
param = params_dict[name]
weight_loader = getattr(param, "weight_loader", None)
if weight_loader is not None:
# Parallel Linears handle TP sharding internally
weight_loader(param, loaded_weight)
else:
default_weight_loader(param, _maybe_shard_weight(loaded_weight, param))
loaded_local.add(name)
# Detach must happen before `DiffusersPipelineLoader._process_weights_after_loading`
# and before any forward pass that triggers layerwise-offload hooks.
self.model._detach_blocks_from_backbones()
return {pipeline_prefix + k for k in loaded_local}
def get_scheduler_time_steps(self, sampling_steps, solver_name="unipc", device=0, shift=5.0):
torch.manual_seed(4)
@@ -375,6 +446,33 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
)[0].squeeze(0)
return video_noise, audio_noise
def encode_prompt(
self,
prompt: str,
video_negative_prompt: str = "",
audio_negative_prompt: str = "",
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Encode the positive and negative prompts via ``self.text_model``.
This is the single text-encoder entrypoint so that the runner-level
prompt-embedding cache (see
``vllm_omni/diffusion/cache/prompt_embed_cache.py``) can transparently
memoize results when the same prompts are submitted repeatedly (e.g.
GRPO rollouts that sample the same prompt with different seeds).
Returns:
(audio_pos, video_pos, video_neg, audio_neg) embeddings cast to
``self.target_dtype``. ``audio_pos`` and ``video_pos`` are the
same tensor, matching the original inline behavior.
"""
text_embeddings = self.text_model(
[prompt, video_negative_prompt, audio_negative_prompt],
device=self.device,
)
text_embeddings = [emb.to(self.target_dtype) for emb in text_embeddings]
# Index 0 is the positive embedding, shared between video and audio branches.
return text_embeddings[0], text_embeddings[0], text_embeddings[1], text_embeddings[2]
def forward(
self,
request: OmniDiffusionRequest,
@@ -432,12 +530,13 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
)
# 3. text embedding
text_embeddings = self.text_model([prompt, video_negative_prompt, audio_negative_prompt], device=self.device)
text_embeddings = [emb.to(self.target_dtype) for emb in text_embeddings]
text_embeddings_audio_pos = text_embeddings[0]
text_embeddings_video_pos = text_embeddings[0]
text_embeddings_video_neg = text_embeddings[1]
text_embeddings_audio_neg = text_embeddings[2]
text_embeddings_audio_pos, text_embeddings_video_pos, text_embeddings_video_neg, text_embeddings_audio_neg = (
self.encode_prompt(
prompt=prompt,
video_negative_prompt=video_negative_prompt,
audio_negative_prompt=audio_negative_prompt,
)
)
video_latent_h, video_latent_w = height // 16, width // 16
+213 -25
View File
@@ -6,6 +6,16 @@ import torch.amp as amp
import torch.nn as nn
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.models.modeling_utils import ModelMixin
from vllm.distributed import (
get_tensor_model_parallel_world_size,
tensor_model_parallel_all_reduce,
)
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
QKVParallelLinear,
RowParallelLinear,
)
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm_omni.diffusion.attention.layer import Attention
@@ -17,7 +27,6 @@ try:
MLPProj,
ModulationAdd,
WanLayerNorm,
WanRMSNorm,
rope_apply, # diff from wan2.2
rope_params,
sinusoidal_embedding_1d,
@@ -26,42 +35,99 @@ except ImportError:
raise ImportError("Failed to import from dependency 'dreamid_omni'.")
class DistributedRMSNorm(nn.Module):
"""RMSNorm that computes global RMS across tensor parallel ranks.
Mirrors `vllm_omni/diffusion/models/wan2_2/wan2_2_transformer.py::DistributedRMSNorm`
"""
def __init__(self, hidden_size: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(hidden_size))
def forward(self, x: torch.Tensor) -> torch.Tensor:
tp_size = get_tensor_model_parallel_world_size()
x_dtype = x.dtype
x_float = x.float()
local_sum_sq = x_float.pow(2).sum(dim=-1, keepdim=True)
local_count = x.shape[-1]
if tp_size > 1:
local_sum_sq = tensor_model_parallel_all_reduce(local_sum_sq)
local_count = local_count * tp_size
rms = torch.sqrt(local_sum_sq / local_count + self.eps)
return (x_float / rms * self.weight.float()).to(x_dtype)
class WanSelfAttention(nn.Module):
"""Optimized self-attention module using vLLM layers."""
def __init__(self, dim, num_heads, window_size=(-1, -1), qk_norm=True, eps=1e-6):
def __init__(
self,
dim,
num_heads,
window_size=(-1, -1),
qk_norm=True,
eps=1e-6,
*,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
assert dim % num_heads == 0
super().__init__()
self.dim = dim
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.window_size = window_size
self.qk_norm = qk_norm
self.eps = eps
# layers
self.q = nn.Linear(dim, dim)
self.k = nn.Linear(dim, dim)
self.v = nn.Linear(dim, dim)
self.o = nn.Linear(dim, dim)
self.norm_q = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
self.norm_k = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
self.to_qkv = QKVParallelLinear(
hidden_size=dim,
head_size=self.head_dim,
total_num_heads=num_heads,
bias=True,
quant_config=quant_config,
prefix=f"{prefix}.to_qkv" if prefix else "to_qkv",
)
self.num_heads = self.to_qkv.num_heads
self.num_kv_heads = self.to_qkv.num_kv_heads
self.tp_inner_dim = self.num_heads * self.head_dim
self.tp_kv_dim = self.num_kv_heads * self.head_dim
self.o = RowParallelLinear(
dim,
dim,
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.o" if prefix else "o",
)
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps) if qk_norm else nn.Identity()
self.norm_k = DistributedRMSNorm(self.tp_kv_dim, eps=eps) if qk_norm else nn.Identity()
# Unified attention layer
self.attn = Attention(
num_heads=self.num_heads,
head_size=self.head_dim,
num_kv_heads=self.num_heads,
num_kv_heads=self.num_kv_heads,
softmax_scale=1.0 / (self.head_dim**0.5),
causal=False,
prefix=prefix,
)
# query, key, value function
def qkv_fn(self, x):
b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
b, s = x.shape[:2]
qkv, _ = self.to_qkv(x)
q_size = self.num_heads * self.head_dim
kv_size = self.num_kv_heads * self.head_dim
q, k, v = qkv.split([q_size, kv_size, kv_size], dim=-1)
q = self.norm_q(self.q(x)).view(b, s, n, d)
k = self.norm_k(self.k(x)).view(b, s, n, d)
v = self.v(x).view(b, s, n, d)
q = self.norm_q(q).view(b, s, self.num_heads, self.head_dim)
k = self.norm_k(k).view(b, s, self.num_kv_heads, self.head_dim)
v = v.view(b, s, self.num_kv_heads, self.head_dim)
return q, k, v
def forward(self, x, seq_lens, grid_sizes, freqs, ref_lengths=None, freqs_scaling=None):
@@ -87,14 +153,97 @@ class WanSelfAttention(nn.Module):
return x
class WanT2VCrossAttention(WanSelfAttention):
def qkv_fn(self, x, context):
b, n, d = x.size(0), self.num_heads, self.head_dim
class WanT2VCrossAttention(nn.Module):
"""Text -> latent cross-attention."""
# compute query, key, value
q = self.norm_q(self.q(x)).view(b, -1, n, d)
k = self.norm_k(self.k(context)).view(b, -1, n, d)
v = self.v(context).view(b, -1, n, d)
def __init__(
self,
dim,
num_heads,
window_size=(-1, -1),
qk_norm=True,
eps=1e-6,
*,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
super().__init__()
assert dim % num_heads == 0
self.dim = dim
self.head_dim = dim // num_heads
self.window_size = window_size
self.qk_norm = qk_norm
self.eps = eps
# Separate Q/K/V — Q's input differs from K/V's input (text context)
self.q = ColumnParallelLinear(
dim,
dim,
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.q" if prefix else "q",
)
self.k = ColumnParallelLinear(
dim,
dim,
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.k" if prefix else "k",
)
self.v = ColumnParallelLinear(
dim,
dim,
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.v" if prefix else "v",
)
tp_size = get_tensor_model_parallel_world_size()
self.num_heads = num_heads // tp_size
self.num_kv_heads = self.num_heads
self.tp_inner_dim = self.num_heads * self.head_dim
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps) if qk_norm else nn.Identity()
self.norm_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps) if qk_norm else nn.Identity()
self.o = RowParallelLinear(
dim,
dim,
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.o" if prefix else "o",
)
# Kept for interface parity with WanSelfAttention;
# the active cross-attention path in DreamID-Omni uses the shared FusionModel.attn.
# Disable kv quant to prevent affecting quality.
self.attn = Attention(
num_heads=self.num_heads,
head_size=self.head_dim,
num_kv_heads=self.num_kv_heads,
softmax_scale=1.0 / (self.head_dim**0.5),
causal=False,
prefix=prefix,
disable_kv_quant=True,
)
def qkv_fn(self, x, context):
b = x.size(0)
q = self.q(x)
k = self.k(context)
v = self.v(context)
q = self.norm_q(q).view(b, -1, self.num_heads, self.head_dim)
k = self.norm_k(k).view(b, -1, self.num_kv_heads, self.head_dim)
v = v.view(b, -1, self.num_kv_heads, self.head_dim)
return q, k, v
@@ -142,6 +291,9 @@ class WanAttentionBlock(nn.Module):
cross_attn_norm=False,
eps=1e-6,
additional_emb_length=None,
*,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
super().__init__()
self.dim = dim
@@ -154,7 +306,15 @@ class WanAttentionBlock(nn.Module):
# layers
self.norm1 = WanLayerNorm(dim, eps)
self.self_attn = WanSelfAttention(dim, num_heads, window_size, qk_norm, eps)
self.self_attn = WanSelfAttention(
dim,
num_heads,
window_size,
qk_norm,
eps,
quant_config=quant_config,
prefix=f"{prefix}.self_attn" if prefix else "self_attn",
)
self.norm3 = WanLayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
if cross_attn_type == "i2v_cross_attn":
assert additional_emb_length is not None, "additional_emb_length should be specified for i2v_cross_attn"
@@ -167,9 +327,32 @@ class WanAttentionBlock(nn.Module):
(-1, -1),
qk_norm,
eps,
quant_config=quant_config,
prefix=f"{prefix}.cross_attn" if prefix else "cross_attn",
)
self.norm2 = WanLayerNorm(dim, eps)
self.ffn = nn.Sequential(nn.Linear(dim, ffn_dim), nn.GELU(approximate="tanh"), nn.Linear(ffn_dim, dim))
# FFN layout: Stay compatible with upstream DreamID-Omni checkpoints
self.ffn = nn.Sequential(
ColumnParallelLinear(
dim,
ffn_dim,
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.ffn.0" if prefix else "ffn.0",
),
nn.GELU(approximate="tanh"),
RowParallelLinear(
ffn_dim,
dim,
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.ffn.2" if prefix else "ffn.2",
),
)
# modulation
self.modulation = ModulationAdd(dim, 6)
@@ -243,6 +426,9 @@ class WanModel(ModelMixin, ConfigMixin):
cross_attn_norm=True,
temporal_rope_scaling_factor=1.0,
eps=1e-6,
*,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
r"""
Initialize the diffusion model backbone.
@@ -357,8 +543,10 @@ class WanModel(ModelMixin, ConfigMixin):
cross_attn_norm,
eps,
additional_emb_length,
quant_config=quant_config,
prefix=f"{prefix}.blocks.{layer_idx}" if prefix else f"blocks.{layer_idx}",
)
for _ in range(num_layers)
for layer_idx in range(num_layers)
]
)
@@ -247,8 +247,10 @@ class ErnieImagePipeline(
@staticmethod
def _is_warmup_request(req: OmniDiffusionRequest) -> bool:
request_ids = getattr(req, "request_ids", None) or ()
return len(request_ids) == 1 and request_ids[0] == "dummy_req_id"
is_dummy_run = getattr(req, "is_dummy_run", None)
if callable(is_dummy_run):
return bool(is_dummy_run())
return OmniDiffusionRequest.is_dummy_run_request_id(getattr(req, "request_id", None))
@staticmethod
def _should_apply_pe(req: OmniDiffusionRequest) -> bool:
@@ -25,7 +25,13 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
from vllm_omni.diffusion.data import DiffusionParallelConfig, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelInput,
SequenceParallelOutput,
)
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
from vllm_omni.diffusion.layers.rope import RotaryEmbedding, apply_rope_to_qk
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
@@ -91,6 +97,7 @@ class Flux2FeedForward(nn.Module):
class Flux2Attention(nn.Module):
def __init__(
self,
parallel_config: DiffusionParallelConfig,
query_dim: int,
heads: int = 8,
dim_head: int = 64,
@@ -106,6 +113,7 @@ class Flux2Attention(nn.Module):
prefix: str = "",
):
super().__init__()
self.parallel_config = parallel_config
self.head_dim = dim_head
self.inner_dim = out_dim if out_dim is not None else dim_head * heads
self.query_dim = query_dim
@@ -206,34 +214,82 @@ class Flux2Attention(nn.Module):
encoder_query = self.norm_added_q(encoder_query)
encoder_key = self.norm_added_k(encoder_key)
query = torch.cat([encoder_query, query], dim=1)
key = torch.cat([encoder_key, key], dim=1)
value = torch.cat([encoder_value, value], dim=1)
if image_rotary_emb is not None:
cos, sin = image_rotary_emb
cos = cos.to(query.dtype)
sin = sin.to(query.dtype)
query = self.rope(query, cos, sin)
key = self.rope(key, cos, sin)
attn_metadata = None
if attention_mask is not None:
if attention_mask.dim() == 3:
attention_mask = attention_mask.unsqueeze(1)
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
hidden_states = self.attn(query, key, value, attn_metadata)
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
if encoder_hidden_states is not None:
context_len = encoder_hidden_states.shape[1]
encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
[context_len, hidden_states.shape[1] - context_len],
dim=1,
sp_size = self.parallel_config.sequence_parallel_size
use_sp_joint_attention = (
sp_size is not None
and sp_size > 1
and is_forward_context_available()
and not get_forward_context().split_text_embed_in_sp
)
# Contiguous for FP8 quantization in RowParallelLinear
encoder_hidden_states = self.to_add_out(encoder_hidden_states.contiguous())
if use_sp_joint_attention and image_rotary_emb is not None:
cos, sin = image_rotary_emb
cos = cos.to(query.dtype)
sin = sin.to(query.dtype)
txt_len = encoder_query.shape[1]
txt_cos, img_cos = cos[:txt_len], cos[txt_len:]
txt_sin, img_sin = sin[:txt_len], sin[txt_len:]
query = self.rope(query, img_cos, img_sin)
key = self.rope(key, img_cos, img_sin)
encoder_query = self.rope(encoder_query, txt_cos, txt_sin)
encoder_key = self.rope(encoder_key, txt_cos, txt_sin)
attn_metadata = AttentionMetadata(
joint_query=encoder_query,
joint_key=encoder_key,
joint_value=encoder_value,
joint_strategy="front",
)
hidden_states_mask: torch.Tensor | None = kwargs.get("hidden_states_mask", None)
encoder_hidden_states_mask: torch.Tensor | None = kwargs.get("encoder_hidden_states_mask", None)
if hidden_states_mask is not None:
attn_metadata.attn_mask = hidden_states_mask
if encoder_hidden_states_mask is not None:
attn_metadata.joint_attn_mask = encoder_hidden_states_mask
hidden_states = self.attn(query, key, value, attn_metadata)
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
txt_len = encoder_hidden_states.shape[1]
encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
[txt_len, hidden_states.shape[1] - txt_len],
dim=1,
)
encoder_hidden_states = self.to_add_out(encoder_hidden_states.contiguous())
else:
query = torch.cat([encoder_query, query], dim=1)
key = torch.cat([encoder_key, key], dim=1)
value = torch.cat([encoder_value, value], dim=1)
query, key = apply_rope_to_qk(self.rope, query, key, image_rotary_emb)
attn_metadata = None
if attention_mask is not None:
if attention_mask.dim() == 3:
attention_mask = attention_mask.unsqueeze(1)
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
hidden_states = self.attn(query, key, value, attn_metadata)
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
context_len = encoder_hidden_states.shape[1]
encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
[context_len, hidden_states.shape[1] - context_len],
dim=1,
)
encoder_hidden_states = self.to_add_out(encoder_hidden_states.contiguous())
else:
query, key = apply_rope_to_qk(self.rope, query, key, image_rotary_emb)
attn_metadata = None
if attention_mask is not None:
if attention_mask.dim() == 3:
attention_mask = attention_mask.unsqueeze(1)
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
hidden_states = self.attn(query, key, value, attn_metadata)
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
hidden_states = self.to_out[0](hidden_states.contiguous())
hidden_states = self.to_out[1](hidden_states)
@@ -250,6 +306,7 @@ class Flux2ParallelSelfAttention(nn.Module):
def __init__(
self,
parallel_config: DiffusionParallelConfig,
query_dim: int,
heads: int = 8,
dim_head: int = 64,
@@ -265,6 +322,7 @@ class Flux2ParallelSelfAttention(nn.Module):
prefix: str = "",
):
super().__init__()
self.parallel_config = parallel_config
self.head_dim = dim_head
self.inner_dim = out_dim if out_dim is not None else dim_head * heads
self.query_dim = query_dim
@@ -327,20 +385,59 @@ class Flux2ParallelSelfAttention(nn.Module):
query = self.norm_q(query)
key = self.norm_k(key)
if image_rotary_emb is not None:
sp_size = self.parallel_config.sequence_parallel_size
text_seq_len = kwargs.get("text_seq_len", None)
use_sp_single_stream = (
sp_size is not None
and sp_size > 1
and text_seq_len is not None
and is_forward_context_available()
and not get_forward_context().split_text_embed_in_sp
)
if use_sp_single_stream and image_rotary_emb is not None:
cos, sin = image_rotary_emb
cos = cos.to(query.dtype)
sin = sin.to(query.dtype)
query = self.rope(query, cos, sin)
key = self.rope(key, cos, sin)
txt_cos, img_cos = cos[:text_seq_len], cos[text_seq_len:]
txt_sin, img_sin = sin[:text_seq_len], sin[text_seq_len:]
attn_metadata = None
if attention_mask is not None:
if attention_mask.dim() == 3:
attention_mask = attention_mask.unsqueeze(1)
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
img_query = query[:, text_seq_len:]
img_key = key[:, text_seq_len:]
img_value = value[:, text_seq_len:]
text_query = query[:, :text_seq_len]
text_key = key[:, :text_seq_len]
text_value = value[:, :text_seq_len]
attn_output = self.attn(query, key, value, attn_metadata)
img_query = self.rope(img_query, img_cos, img_sin)
img_key = self.rope(img_key, img_cos, img_sin)
text_query = self.rope(text_query, txt_cos, txt_sin)
text_key = self.rope(text_key, txt_cos, txt_sin)
attn_metadata = AttentionMetadata(
joint_query=text_query,
joint_key=text_key,
joint_value=text_value,
joint_strategy="front",
)
hidden_states_mask: torch.Tensor | None = kwargs.get("hidden_states_mask", None)
encoder_hidden_states_mask: torch.Tensor | None = kwargs.get("encoder_hidden_states_mask", None)
if hidden_states_mask is not None:
attn_metadata.attn_mask = hidden_states_mask
if encoder_hidden_states_mask is not None:
attn_metadata.joint_attn_mask = encoder_hidden_states_mask
attn_output = self.attn(img_query, img_key, img_value, attn_metadata)
else:
query, key = apply_rope_to_qk(self.rope, query, key, image_rotary_emb)
attn_metadata = None
if attention_mask is not None:
if attention_mask.dim() == 3:
attention_mask = attention_mask.unsqueeze(1)
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
attn_output = self.attn(query, key, value, attn_metadata)
attn_output = attn_output.flatten(2, 3).to(query.dtype)
mlp_hidden_states = self.mlp_act_fn(mlp_hidden_states)
@@ -352,6 +449,7 @@ class Flux2ParallelSelfAttention(nn.Module):
class Flux2SingleTransformerBlock(nn.Module):
def __init__(
self,
parallel_config: DiffusionParallelConfig,
dim: int,
num_attention_heads: int,
attention_head_dim: int,
@@ -364,6 +462,7 @@ class Flux2SingleTransformerBlock(nn.Module):
super().__init__()
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
self.attn = Flux2ParallelSelfAttention(
parallel_config=parallel_config,
query_dim=dim,
dim_head=attention_head_dim,
heads=num_attention_heads,
@@ -387,6 +486,13 @@ class Flux2SingleTransformerBlock(nn.Module):
split_hidden_states: bool = False,
text_seq_len: int | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""
Forward pass for Flux2SingleTransformerBlock with SP support.
In SP mode: image hidden_states is chunked (B, img_len/SP, D),
text encoder_hidden_states is full (B, txt_len, D).
The block concatenates them for joint attention.
"""
if encoder_hidden_states is not None:
text_seq_len = encoder_hidden_states.shape[1]
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
@@ -400,6 +506,7 @@ class Flux2SingleTransformerBlock(nn.Module):
attn_output = self.attn(
hidden_states=norm_hidden_states,
image_rotary_emb=image_rotary_emb,
text_seq_len=text_seq_len,
**joint_attention_kwargs,
)
@@ -416,6 +523,7 @@ class Flux2SingleTransformerBlock(nn.Module):
class Flux2TransformerBlock(nn.Module):
def __init__(
self,
parallel_config: DiffusionParallelConfig,
dim: int,
num_attention_heads: int,
attention_head_dim: int,
@@ -432,6 +540,7 @@ class Flux2TransformerBlock(nn.Module):
self.norm1_context = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
self.attn = Flux2Attention(
parallel_config=parallel_config,
query_dim=dim,
added_kv_proj_dim=dim,
dim_head=attention_head_dim,
@@ -543,6 +652,47 @@ class Flux2PosEmbed(nn.Module):
return freqs_cos, freqs_sin
class Flux2RopePrepare(nn.Module):
"""Prepares RoPE embeddings for sequence parallel.
This module encapsulates the RoPE computation for Flux.2-dev.
For dual-stream attention, text components (outputs 0, 1) are replicated
across SP ranks, while image components (outputs 2, 3) are sharded.
NOTE: The hidden_states projection is handled separately in forward()
so that _sp_plan can shard it at the root level.
"""
def __init__(self, pos_embed: Flux2PosEmbed):
super().__init__()
self.pos_embed = pos_embed
def forward(
self,
img_ids: torch.Tensor,
txt_ids: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Compute RoPE embeddings for text and image sequences.
Args:
img_ids: Image position IDs (img_seq_len, n_axes)
txt_ids: Text position IDs (txt_seq_len, n_axes)
Returns:
Tuple of cosine / sine components for text & image
in the order: (txt_cos, txt_sin, img_cos, img_sin)
NOTE: careful about output orders if this is refactored in the
future; we need to match the _sp_plan indices, since text
components (0 & 1) need to be replicated across SP ranks,
while image components (2 & 3) must be sharded.
"""
img_freqs_cos, img_freqs_sin = self.pos_embed(img_ids)
txt_freqs_cos, txt_freqs_sin = self.pos_embed(txt_ids)
return txt_freqs_cos, txt_freqs_sin, img_freqs_cos, img_freqs_sin
class Flux2TimestepGuidanceEmbeddings(nn.Module):
def __init__(
self,
@@ -601,9 +751,22 @@ class Flux2Modulation(nn.Module):
class Flux2Transformer2DModel(nn.Module):
"""
The Transformer model introduced in Flux 2.
Supports Sequence Parallelism (Ulysses and Ring) when configured via OmniDiffusionConfig.
"""
_repeated_blocks = ["Flux2TransformerBlock", "Flux2SingleTransformerBlock"]
_sp_plan = {
"": {
"hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, auto_pad=True),
},
"rope_prepare": {
2: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
3: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
},
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
}
"""SP plan: shard hidden_states at root level, shard img_freqs at rope_prepare, gather output at proj_out."""
@staticmethod
def _is_transformer_block(name: str, module) -> bool:
@@ -628,6 +791,7 @@ class Flux2Transformer2DModel(nn.Module):
eps: float = 1e-6,
guidance_embeds: bool = True,
quant_config: "QuantizationConfig | None" = None,
od_config: OmniDiffusionConfig | None = None,
):
super().__init__()
self.guidance_embeds = guidance_embeds
@@ -652,7 +816,13 @@ class Flux2Transformer2DModel(nn.Module):
guidance_embeds=guidance_embeds,
)
if od_config is not None:
self.parallel_config = od_config.parallel_config
else:
self.parallel_config = DiffusionParallelConfig()
self.pos_embed = Flux2PosEmbed(theta=rope_theta, axes_dim=axes_dims_rope)
self.rope_prepare = Flux2RopePrepare(self.pos_embed)
self.time_guidance_embed = Flux2TimestepGuidanceEmbeddings(
in_channels=timestep_guidance_channels,
embedding_dim=self.inner_dim,
@@ -670,6 +840,7 @@ class Flux2Transformer2DModel(nn.Module):
self.transformer_blocks = nn.ModuleList(
[
Flux2TransformerBlock(
parallel_config=self.parallel_config,
dim=self.inner_dim,
num_attention_heads=num_attention_heads,
attention_head_dim=attention_head_dim,
@@ -686,6 +857,7 @@ class Flux2Transformer2DModel(nn.Module):
self.single_transformer_blocks = nn.ModuleList(
[
Flux2SingleTransformerBlock(
parallel_config=self.parallel_config,
dim=self.inner_dim,
num_attention_heads=num_attention_heads,
attention_head_dim=attention_head_dim,
@@ -722,6 +894,9 @@ class Flux2Transformer2DModel(nn.Module):
joint_attention_kwargs = joint_attention_kwargs or {}
num_txt_tokens = encoder_hidden_states.shape[1]
sp_size = self.parallel_config.sequence_parallel_size
if sp_size and sp_size > 1 and is_forward_context_available():
get_forward_context().split_text_embed_in_sp = False
timestep = timestep.to(hidden_states.dtype) * 1000
if guidance is not None:
@@ -742,18 +917,43 @@ class Flux2Transformer2DModel(nn.Module):
txt_ids = txt_ids[0]
if is_torch_npu_available():
freqs_cos_image, freqs_sin_image = self.pos_embed(img_ids.cpu())
image_rotary_emb = (freqs_cos_image.npu(), freqs_sin_image.npu())
freqs_cos_text, freqs_sin_text = self.pos_embed(txt_ids.cpu())
text_rotary_emb = (freqs_cos_text.npu(), freqs_sin_text.npu())
txt_freqs_cos, txt_freqs_sin, img_freqs_cos, img_freqs_sin = self.rope_prepare(img_ids.cpu(), txt_ids.cpu())
txt_freqs_cos = txt_freqs_cos.npu()
txt_freqs_sin = txt_freqs_sin.npu()
img_freqs_cos = img_freqs_cos.npu()
img_freqs_sin = img_freqs_sin.npu()
else:
image_rotary_emb = self.pos_embed(img_ids)
text_rotary_emb = self.pos_embed(txt_ids)
txt_freqs_cos, txt_freqs_sin, img_freqs_cos, img_freqs_sin = self.rope_prepare(img_ids, txt_ids)
concat_rotary_emb = (
torch.cat([text_rotary_emb[0], image_rotary_emb[0]], dim=0),
torch.cat([text_rotary_emb[1], image_rotary_emb[1]], dim=0),
torch.cat([txt_freqs_cos, img_freqs_cos], dim=0),
torch.cat([txt_freqs_sin, img_freqs_sin], dim=0),
)
# Create separate masks for image and text portions for Ulysses SP joint attention
hidden_states_mask = None
encoder_hidden_states_mask = None
if is_forward_context_available():
ctx = get_forward_context()
else:
ctx = None
if ctx is not None and ctx.sp_original_seq_len is not None and ctx.sp_padding_size > 0:
batch_size = hidden_states.shape[0]
img_padded_seq_len = ctx.sp_original_seq_len + ctx.sp_padding_size
hidden_states_mask = torch.ones(
batch_size,
img_padded_seq_len,
dtype=torch.bool,
device=hidden_states.device,
)
hidden_states_mask[:, ctx.sp_original_seq_len :] = False
if hidden_states_mask.all():
hidden_states_mask = None
if hidden_states_mask is not None:
joint_attention_kwargs["hidden_states_mask"] = hidden_states_mask
if encoder_hidden_states_mask is not None:
joint_attention_kwargs["encoder_hidden_states_mask"] = encoder_hidden_states_mask
for index_block, block in enumerate(self.transformer_blocks):
encoder_hidden_states, hidden_states = block(
hidden_states=hidden_states,
@@ -773,6 +973,7 @@ class Flux2Transformer2DModel(nn.Module):
temb_mod_params=single_stream_mod,
image_rotary_emb=concat_rotary_emb,
joint_attention_kwargs=joint_attention_kwargs,
text_seq_len=num_txt_tokens,
)
hidden_states = hidden_states[:, num_txt_tokens:, ...]
@@ -398,7 +398,9 @@ class Flux2Pipeline(nn.Module, CFGParallelMixin, SupportImageInput, ProgressBarM
self._execution_device
)
transformer_kwargs = get_transformer_config_kwargs(od_config.tf_model_config, Flux2Transformer2DModel)
self.transformer = Flux2Transformer2DModel(quant_config=od_config.quantization_config, **transformer_kwargs)
self.transformer = Flux2Transformer2DModel(
quant_config=od_config.quantization_config, od_config=od_config, **transformer_kwargs
)
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
self.image_processor = Flux2ImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
@@ -15,6 +15,7 @@ from vllm.logger import init_logger
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
QKVParallelLinear,
ReplicatedLinear,
RowParallelLinear,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
@@ -33,6 +34,9 @@ from vllm_omni.diffusion.distributed.sp_plan import (
)
from vllm_omni.diffusion.forward_context import get_forward_context
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
logger = init_logger(__name__)
@@ -230,11 +234,24 @@ class GlmImagePrepare(nn.Module):
class GlmImageAdaLayerNormZero(nn.Module):
"""Adaptive LayerNorm with zero initialization for both image and text streams."""
def __init__(self, embedding_dim: int, dim: int) -> None:
def __init__(
self,
embedding_dim: int,
dim: int,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
) -> None:
super().__init__()
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
self.norm_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
self.linear = nn.Linear(embedding_dim, 12 * dim, bias=True)
self.linear = ReplicatedLinear(
embedding_dim,
12 * dim,
bias=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.linear",
)
def forward(
self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
@@ -244,6 +261,8 @@ class GlmImageAdaLayerNormZero(nn.Module):
norm_encoder_hidden_states = self.norm_context(encoder_hidden_states).to(dtype=dtype)
emb = self.linear(temb)
if isinstance(emb, tuple):
emb = emb[0]
(
shift_msa,
c_shift_msa,
@@ -286,14 +305,25 @@ class GlmImageAdaLayerNormContinuous(nn.Module):
elementwise_affine: bool = True,
eps: float = 1e-5,
bias: bool = True,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
super().__init__()
self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
self.linear = ReplicatedLinear(
conditioning_embedding_dim,
embedding_dim * 2,
bias=bias,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.linear",
)
self.norm = nn.LayerNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
# NO SiLU here
emb = self.linear(conditioning_embedding.to(x.dtype))
if isinstance(emb, tuple):
emb = emb[0]
scale, shift = torch.chunk(emb, 2, dim=1)
x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
return x
@@ -469,6 +499,7 @@ class GlmImageAttention(nn.Module):
out_bias: bool = True,
eps: float = 1e-5,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
super().__init__()
self.dim = dim
@@ -485,6 +516,7 @@ class GlmImageAttention(nn.Module):
bias=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.to_qkv",
)
# QK normalization (LayerNorm, not RMSNorm for GLM-Image)
@@ -501,6 +533,7 @@ class GlmImageAttention(nn.Module):
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.to_out.0",
),
nn.Dropout(0.0),
]
@@ -554,7 +587,7 @@ class GlmImageAttention(nn.Module):
hidden_states_combined = torch.cat([encoder_hidden_states, hidden_states], dim=1)
# QKV projection
qkv = self.to_qkv(hidden_states_combined)
qkv = self.to_qkv(hidden_states_combined.contiguous())
q_size = self.to_qkv.num_heads * self.head_dim
kv_size = self.to_qkv.num_kv_heads * self.head_dim
query, key, value = qkv.split([q_size, kv_size, kv_size], dim=-1)
@@ -604,8 +637,12 @@ class GlmImageAttention(nn.Module):
# Project combined [text, image] outputs, then split.
# This keeps SP numerically aligned with the non-SP path.
joint_hidden_states_out = joint_hidden_states_out.flatten(2, 3).to(dtype)
# Contiguous for FP8/W4A16 quantized RowParallelLinear
for module in self.to_out:
joint_hidden_states_out = module(joint_hidden_states_out)
if isinstance(module, RowParallelLinear):
joint_hidden_states_out = module(joint_hidden_states_out.contiguous())
else:
joint_hidden_states_out = module(joint_hidden_states_out)
encoder_hidden_states_out = joint_hidden_states_out[:, :text_seq_length, :]
hidden_states_out = joint_hidden_states_out[:, text_seq_length:, :]
@@ -645,7 +682,10 @@ class GlmImageAttention(nn.Module):
# Output projection
for module in self.to_out:
hidden_states_out = module(hidden_states_out)
if isinstance(module, RowParallelLinear):
hidden_states_out = module(hidden_states_out.contiguous())
else:
hidden_states_out = module(hidden_states_out)
# Split back to text and image
encoder_hidden_states_out = hidden_states_out[:, :text_seq_length, :]
@@ -663,6 +703,7 @@ class ColumnParallelGELU(nn.Module):
approximate: str = "none",
bias: bool = True,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
super().__init__()
self.proj = ColumnParallelLinear(
@@ -672,6 +713,7 @@ class ColumnParallelGELU(nn.Module):
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.proj",
)
self.approximate = approximate
@@ -688,6 +730,7 @@ class ColumnParallelSiLU(nn.Module):
*,
bias: bool = True,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
super().__init__()
self.proj = ColumnParallelLinear(
@@ -697,6 +740,7 @@ class ColumnParallelSiLU(nn.Module):
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.proj",
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
@@ -714,6 +758,7 @@ class GlmImageFeedForward(nn.Module):
bias: bool = True,
activation_fn: str = "gelu",
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
super().__init__()
inner_dim = inner_dim or int(dim * mult)
@@ -721,7 +766,7 @@ class GlmImageFeedForward(nn.Module):
if activation_fn == "linear-silu":
layers: list[nn.Module] = [
ColumnParallelSiLU(dim, inner_dim, bias=bias, quant_config=quant_config),
ColumnParallelSiLU(dim, inner_dim, bias=bias, quant_config=quant_config, prefix=f"{prefix}.net.0"),
nn.Identity(),
RowParallelLinear(
inner_dim,
@@ -730,12 +775,20 @@ class GlmImageFeedForward(nn.Module):
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.net.2",
),
]
else:
approximate = "tanh" if activation_fn == "gelu-approximate" else "none"
layers = [
ColumnParallelGELU(dim, inner_dim, approximate=approximate, bias=bias, quant_config=quant_config),
ColumnParallelGELU(
dim,
inner_dim,
approximate=approximate,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.net.0",
),
nn.Identity(),
RowParallelLinear(
inner_dim,
@@ -744,6 +797,7 @@ class GlmImageFeedForward(nn.Module):
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.net.2",
),
]
@@ -751,7 +805,12 @@ class GlmImageFeedForward(nn.Module):
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
for module in self.net:
hidden_states = module(hidden_states)
if isinstance(module, ColumnParallelLinear):
hidden_states, _ = module(hidden_states)
elif isinstance(module, RowParallelLinear):
hidden_states = module(hidden_states.contiguous())
else:
hidden_states = module(hidden_states)
return hidden_states
@@ -765,19 +824,21 @@ class GlmImageTransformerBlock(nn.Module):
attention_head_dim: int = 40,
time_embed_dim: int = 512,
ffn_hidden_dim: int | None = None,
quant_config: "QuantizationConfig | None" = None,
parallel_config: DiffusionParallelConfig | None = None,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
) -> None:
super().__init__()
# 1. Attention with AdaLN
self.norm1 = GlmImageAdaLayerNormZero(time_embed_dim, dim)
self.norm1 = GlmImageAdaLayerNormZero(time_embed_dim, dim, quant_config=quant_config, prefix=f"{prefix}.norm1")
self.attn1 = GlmImageAttention(
dim=dim,
num_heads=num_attention_heads,
head_dim=attention_head_dim,
quant_config=quant_config,
parallel_config=parallel_config,
quant_config=quant_config,
prefix=f"{prefix}.attn1",
)
# 2. Feedforward
@@ -789,6 +850,7 @@ class GlmImageTransformerBlock(nn.Module):
inner_dim=ffn_hidden_dim,
activation_fn="gelu-approximate",
quant_config=quant_config,
prefix=f"{prefix}.ff",
)
def forward(
@@ -959,6 +1021,7 @@ class GlmImageTransformer2DModel(CachedTransformer):
inner_dim=inner_dim,
activation_fn="gelu",
quant_config=quant_config,
prefix="glyph_projector",
)
self.prior_token_embedding = nn.Embedding(prior_vq_quantizer_codebook_size, inner_dim)
self.prior_projector = GlmImageFeedForward(
@@ -967,6 +1030,7 @@ class GlmImageTransformer2DModel(CachedTransformer):
inner_dim=inner_dim,
activation_fn="linear-silu",
quant_config=quant_config,
prefix="prior_projector",
)
# Prepare module for SP (encapsulates patch embedding and RoPE for _sp_plan)
@@ -988,15 +1052,20 @@ class GlmImageTransformer2DModel(CachedTransformer):
attention_head_dim,
time_embed_dim,
ffn_hidden_dim=ffn_hidden_dim,
quant_config=quant_config,
parallel_config=self.parallel_config,
quant_config=quant_config,
prefix=f"transformer_blocks.{i}",
)
for _ in range(num_layers)
for i in range(num_layers)
]
)
# 4. Output projection
self.norm_out = GlmImageAdaLayerNormContinuous(inner_dim, time_embed_dim, elementwise_affine=False)
# Final modulation feeds proj_out; quant_config is NOT applied here
# to avoid precision degradation in the final projection layer.
self.norm_out = GlmImageAdaLayerNormContinuous(
inner_dim, time_embed_dim, elementwise_affine=False, quant_config=None, prefix="norm_out"
)
self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels, bias=True)
def forward(
@@ -301,10 +301,7 @@ class GlmImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
# Load transformer (DiT)
logger.info("Loading GlmImageTransformer2DModel (DiT)...")
self.transformer = GlmImageTransformer2DModel(
od_config=od_config,
quant_config=od_config.quantization_config,
)
self.transformer = GlmImageTransformer2DModel(od_config=od_config, quant_config=od_config.quantization_config)
# Weight sources for DiT loading
self.weights_sources = [
@@ -689,15 +686,11 @@ class GlmImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
prompt = first_prompt if isinstance(first_prompt, str) else (first_prompt.get("prompt") or "")
# NOTE: DiffusionEngine does an internal warmup "dummy run" during
# initialization. That request has no request_id and does not carry
# initialization. That request carries the fixed dummy request_id and does not carry
# Stage-0 (AR) outputs via req.extra. For GLM-Image, we allow that
# specific warmup request to proceed by synthesizing minimal prior
# tokens, while still raising a clear error for real requests.
is_dummy_warmup = (
not getattr(req, "request_id", None)
and prompt == "dummy run"
and (req.sampling_params.num_inference_steps == 1)
)
is_dummy_warmup = req.is_dummy_run()
# Get pre-computed prompt embeddings if provided
if isinstance(first_prompt, str):
@@ -3,6 +3,7 @@
# Adapted from Helios (https://github.com/BestWishYsh/Helios)
import math
from collections import OrderedDict
from collections.abc import Iterable
from functools import lru_cache
from typing import TYPE_CHECKING, Any
@@ -447,21 +448,32 @@ class HeliosCrossAttention(nn.Module):
causal=False,
)
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor,
) -> torch.Tensor:
query = self.to_q(hidden_states)
query = self.norm_q(query)
def project_kv(self, encoder_hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
key = self.to_k(encoder_hidden_states)
value = self.to_v(encoder_hidden_states)
key = self.norm_k(key)
query = query.unflatten(2, (self.num_heads, self.head_dim))
key = key.unflatten(2, (self.num_heads, self.head_dim))
value = value.unflatten(2, (self.num_heads, self.head_dim))
return key, value
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor | None = None,
encoder_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> torch.Tensor:
query = self.to_q(hidden_states)
query = self.norm_q(query)
if encoder_key_value is None:
if encoder_hidden_states is None:
raise ValueError("encoder_hidden_states is required when encoder_key_value is not provided.")
key, value = self.project_kv(encoder_hidden_states)
else:
key, value = encoder_key_value
query = query.unflatten(2, (self.num_heads, self.head_dim))
hidden_states = self.attn(query, key, value)
hidden_states = hidden_states.flatten(2, 3)
@@ -526,6 +538,7 @@ class HeliosTransformerBlock(nn.Module):
temb: torch.Tensor,
rotary_emb: torch.Tensor,
original_context_length: int | None = None,
cross_attn_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> torch.Tensor:
if temb.ndim == 4:
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
@@ -556,12 +569,20 @@ class HeliosTransformerBlock(nn.Module):
hidden_states[:, history_seq_len:],
)
norm_hidden_states = self.norm2(current_hidden_states.float()).type_as(current_hidden_states)
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states)
attn_output = self.attn2(
norm_hidden_states,
encoder_hidden_states,
encoder_key_value=cross_attn_key_value,
)
current_hidden_states = current_hidden_states + attn_output
hidden_states = torch.cat([history_hidden_states, current_hidden_states], dim=1)
else:
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states)
attn_output = self.attn2(
norm_hidden_states,
encoder_hidden_states,
encoder_key_value=cross_attn_key_value,
)
hidden_states = hidden_states + attn_output
# 3. Feed-forward
@@ -723,11 +744,80 @@ class HeliosTransformer3DModel(nn.Module):
# 5. Output norm & projection
self.norm_out = HeliosOutputNorm(inner_dim, eps)
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
self._projected_encoder_cache: OrderedDict[tuple, torch.Tensor] = OrderedDict()
self._cross_attn_kv_cache: OrderedDict[tuple, list[tuple[torch.Tensor, torch.Tensor]]] = OrderedDict()
self._cross_attn_cache_size = 2
@property
def dtype(self) -> torch.dtype:
return next(self.parameters()).dtype
@staticmethod
def _tensor_cache_key(tensor: torch.Tensor) -> tuple:
try:
version = tensor._version
except RuntimeError:
version = None
return (
tensor.data_ptr(),
tuple(tensor.shape),
tuple(tensor.stride()),
tensor.dtype,
tensor.device.type,
tensor.device.index,
version,
)
@staticmethod
def _get_from_lru(cache: OrderedDict, key: tuple):
value = cache.get(key)
if value is not None:
cache.move_to_end(key)
return value
def _put_lru(self, cache: OrderedDict, key: tuple, value) -> None:
cache[key] = value
cache.move_to_end(key)
while len(cache) > self._cross_attn_cache_size:
cache.popitem(last=False)
def clear_cross_attention_cache(self) -> None:
self._projected_encoder_cache.clear()
self._cross_attn_kv_cache.clear()
def _cache_enabled(self) -> bool:
return not self.training and not torch.is_grad_enabled() and not torch.compiler.is_compiling()
def _project_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
if not self._cache_enabled():
return self.condition_embedder.text_embedder(encoder_hidden_states)
cache_key = self._tensor_cache_key(encoder_hidden_states)
cached = self._get_from_lru(self._projected_encoder_cache, cache_key)
if cached is not None:
return cached
projected = self.condition_embedder.text_embedder(encoder_hidden_states)
self._put_lru(self._projected_encoder_cache, cache_key, projected)
return projected
def _get_cross_attn_key_values(
self,
encoder_hidden_states: torch.Tensor,
) -> list[tuple[torch.Tensor, torch.Tensor]] | None:
if not self._cache_enabled():
return None
cache_key = self._tensor_cache_key(encoder_hidden_states)
cached = self._get_from_lru(self._cross_attn_kv_cache, cache_key)
if cached is not None:
return cached
key_values = [block.attn2.project_kv(encoder_hidden_states) for block in self.blocks]
self._put_lru(self._cross_attn_kv_cache, cache_key, key_values)
return key_values
def forward(
self,
hidden_states: torch.Tensor,
@@ -836,7 +926,12 @@ class HeliosTransformer3DModel(nn.Module):
.expand(batch_size, -1, history_context_length, -1)
)
temb, timestep_proj, encoder_hidden_states = self.condition_embedder(timestep, encoder_hidden_states)
temb, timestep_proj, _ = self.condition_embedder(
timestep,
encoder_hidden_states,
is_return_encoder_hidden_states=False,
)
encoder_hidden_states = self._project_encoder_hidden_states(encoder_hidden_states)
timestep_proj = timestep_proj.unflatten(-1, (6, -1))
if indices_hidden_states is not None and not self.zero_history_timestep:
@@ -857,14 +952,17 @@ class HeliosTransformer3DModel(nn.Module):
hidden_states = hidden_states.contiguous()
encoder_hidden_states = encoder_hidden_states.contiguous()
rotary_emb = rotary_emb.contiguous()
cross_attn_key_values = self._get_cross_attn_key_values(encoder_hidden_states)
for block in self.blocks:
for block_idx, block in enumerate(self.blocks):
cross_attn_key_value = None if cross_attn_key_values is None else cross_attn_key_values[block_idx]
hidden_states = block(
hidden_states,
encoder_hidden_states,
timestep_proj,
rotary_emb,
original_context_length,
cross_attn_key_value,
)
# 7. Output normalization
@@ -0,0 +1,17 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""HiDream Image diffusion model components."""
from vllm_omni.diffusion.models.hidream_image.hidream_image_transformer import (
HiDreamImageTransformer2DModel,
)
from vllm_omni.diffusion.models.hidream_image.pipeline_hidream_image import (
HiDreamImagePipeline,
get_hidream_image_post_process_func,
)
__all__ = [
"HiDreamImageTransformer2DModel",
"HiDreamImagePipeline",
"get_hidream_image_post_process_func",
]
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -891,6 +891,7 @@ class ImageKVCacheManager:
# cache related
self.image_token_len: int = image_token_len
self.image_kv_cache_map: tuple[torch.Tensor, torch.Tensor] | None = None
self.image_kv_cache_lens: torch.Tensor | None = None
self._injected_ar_kv: list[tuple[torch.Tensor, torch.Tensor]] | None = None
self.sp_size = get_sequence_parallel_world_size()
@@ -904,12 +905,23 @@ class ImageKVCacheManager:
prefix=f"{prefix}.attn" if prefix else "",
)
@staticmethod
def _get_current_starts(
gen_timestep_scatter_index: torch.Tensor | None,
ar_kv_len: int = 0,
) -> torch.Tensor:
assert gen_timestep_scatter_index is not None, (
"`gen_timestep_scatter_index` is required to locate the generated image timestep token for image KV reuse."
)
return gen_timestep_scatter_index[:, -1].to(dtype=torch.long) + ar_kv_len
def _cache_prompt_kv(
self,
key: torch.Tensor,
value: torch.Tensor,
seq_len: int,
shard_image_size: int | None = None,
gen_timestep_scatter_index: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Cache prompt KV on first_step. Consumes _injected_ar_kv.
@@ -939,12 +951,26 @@ class ImageKVCacheManager:
key = torch.cat(new_keys, dim=0)
value = torch.cat(new_values, dim=0)
image_size = shard_image_size if self.sp_size > 1 else (self.image_token_len + 1)
cached_prompt_len = seq_len - image_size
cached_prompt_lens = self._get_current_starts(gen_timestep_scatter_index, ar_kv_len)
assert torch.all(cached_prompt_lens <= key.shape[1]), (
f"cached_prompt_lens({cached_prompt_lens.tolist()}) must be <= key length({key.shape[1]})"
)
if shard_image_size is not None:
expected_prompt_len = seq_len - shard_image_size
assert torch.all(cached_prompt_lens == expected_prompt_len), (
f"cached_prompt_lens({cached_prompt_lens.tolist()}) != "
f"seq_len({seq_len}) - shard_image_size({shard_image_size})"
)
cached_key = key[:, :cached_prompt_len].reshape(-1, num_kv_heads, head_dim)
cached_value = value[:, :cached_prompt_len].reshape(-1, num_kv_heads, head_dim)
max_cached_prompt_len = int(cached_prompt_lens.max().item())
cached_key = key.new_zeros(bs, max_cached_prompt_len, num_kv_heads, head_dim)
cached_value = value.new_zeros(bs, max_cached_prompt_len, num_kv_heads, head_dim)
for b in range(bs):
cached_prompt_len = int(cached_prompt_lens[b].item())
cached_key[b, :cached_prompt_len] = key[b, :cached_prompt_len]
cached_value[b, :cached_prompt_len] = value[b, :cached_prompt_len]
self.image_kv_cache_map = (cached_key, cached_value)
self.image_kv_cache_lens = cached_prompt_lens
return key, value
def _reuse_prompt_kv(
@@ -954,42 +980,36 @@ class ImageKVCacheManager:
seq_len: int,
bs: int,
shard_image_size: int | None = None,
position_ids: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Reuse cached prompt KV in subsequent denoising steps.
Non-SP: returns [cached_prompt, new_image, zero_eoi] shaped [bs, seq_len, ...].
SP: returns cached prompt only shaped [bs, cached_prompt_len, ...] (used as joint_text).
Non-SP: concatenates cached prompt KV with current image KV.
SP: returns cached prompt KV only (used as joint_text).
"""
cached_key, cached_value = self.image_kv_cache_map
_, q_len, num_kv_heads, head_dim = key.shape
cached_prompt_len = cached_key.shape[0] // bs
_, q_len, _, _ = key.shape
assert cached_key.dim() == 4 and cached_key.shape[0] == bs
max_cached_prompt_len = cached_key.shape[1]
if shard_image_size is not None:
assert cached_prompt_len == seq_len - q_len
result_k = cached_key.reshape(bs, cached_prompt_len, num_kv_heads, head_dim)
result_v = cached_value.reshape(bs, cached_prompt_len, num_kv_heads, head_dim)
return result_k.contiguous(), result_v.contiguous()
assert max_cached_prompt_len + q_len == seq_len, (
f"max_cached_prompt_len({max_cached_prompt_len}) + q_len({q_len}) != seq_len({seq_len})"
)
return cached_key.contiguous(), cached_value.contiguous()
assert cached_prompt_len + 1 == seq_len - q_len, f"{cached_prompt_len + 1} != {seq_len - q_len}"
key = key.reshape(-1, num_kv_heads, head_dim)
value = value.reshape(-1, num_kv_heads, head_dim)
zero_eoi = torch.zeros(1, num_kv_heads, head_dim, device=key.device, dtype=key.dtype)
new_key, new_value = [], []
for b in range(bs):
cache_base = b * cached_prompt_len
img_base = b * q_len
new_key.append(cached_key[cache_base : cache_base + cached_prompt_len])
new_key.append(key[img_base : img_base + q_len])
new_key.append(zero_eoi)
new_value.append(cached_value[cache_base : cache_base + cached_prompt_len])
new_value.append(value[img_base : img_base + q_len])
new_value.append(zero_eoi)
new_key = torch.cat(new_key).reshape(bs, seq_len, num_kv_heads, head_dim)
new_value = torch.cat(new_value).reshape(bs, seq_len, num_kv_heads, head_dim)
assert max_cached_prompt_len + q_len == seq_len, (
f"max_cached_prompt_len({max_cached_prompt_len}) + q_len({q_len}) != seq_len({seq_len})"
)
assert self.image_kv_cache_lens is not None
if position_ids is not None:
assert position_ids.shape == (bs, q_len)
assert torch.all(position_ids[:, 0] == self.image_kv_cache_lens), (
"The first current position must immediately follow each sample's cached prompt KV."
)
new_key = torch.cat([cached_key, key], dim=1)
new_value = torch.cat([cached_value, value], dim=1)
return new_key.contiguous(), new_value.contiguous()
def _build_neg_ar_kv(
@@ -1032,7 +1052,7 @@ class ImageKVCacheManager:
query_lens = kwargs.get("query_lens")
seq_lens = kwargs.get("seq_lens")
shard_image_size = kwargs.get("shard_image_size")
shard_image_size = kwargs.get("shard_image_size") if self.sp_size > 1 else None
bs = len(query_lens)
q_len = query_lens[0]
seq_len = seq_lens[0]
@@ -1058,7 +1078,14 @@ class ImageKVCacheManager:
value = value[:, :0, :, :]
elif first_step:
self.image_kv_cache_map = None # reset first
key, value = self._cache_prompt_kv(key, value, seq_len, shard_image_size)
self.image_kv_cache_lens = None
key, value = self._cache_prompt_kv(
key,
value,
seq_len,
shard_image_size,
kwargs.get("gen_timestep_scatter_index"),
)
if self.sp_size > 1:
local_prompt_len = seq_len - shard_image_size
join_query_len = query.shape[1] - shard_image_size
@@ -1070,7 +1097,7 @@ class ImageKVCacheManager:
value = value[:, local_prompt_len:, :, :]
else:
if self.sp_size <= 1:
key, value = self._reuse_prompt_kv(key, value, seq_len, bs)
key, value = self._reuse_prompt_kv(key, value, seq_len, bs, position_ids=kwargs.get("position_ids"))
else:
joint_text_query = query[:, :0, :, :]
joint_text_key, joint_text_value = self._reuse_prompt_kv(key, value, seq_len, bs, shard_image_size)
@@ -1814,6 +1841,7 @@ class HunyuanImage3DecoderLayer(nn.Module):
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
custom_pos_emb=custom_pos_emb,
past_key_value=past_key_value,
output_attentions=output_attentions,
@@ -1878,12 +1906,21 @@ class HunyuanImagePreprocessor(nn.Module):
image_token_len: int,
is_first_step: bool = False,
uncond_cfg_prefill: bool = False,
gen_timestep_scatter_index: torch.Tensor | None = None,
):
# ---------- compute prompt length ----------
if uncond_cfg_prefill:
prompt_len = hidden_states.shape[1]
elif is_first_step:
prompt_len = hidden_states.shape[1] - image_token_len - 1
assert gen_timestep_scatter_index is not None, (
"`gen_timestep_scatter_index` is required to split prompt and "
"generated image tokens for sequence parallel image generation."
)
prompt_lens = gen_timestep_scatter_index[:, -1]
assert torch.all(prompt_lens == prompt_lens[0]), (
"Sequence parallel image generation requires the generated timestep position to match across the batch."
)
prompt_len = int(prompt_lens[0].item())
else:
prompt_len = 0
@@ -2073,7 +2110,7 @@ class HunyuanImage3Model(nn.Module):
return False
def is_scalar_quant_scale(name: str, tensor: torch.Tensor) -> bool:
return tensor.numel() == 1 and name.endswith((".input_scale", ".weight_scale"))
return tensor.numel() == 1 and name.endswith((".input_scale", ".weight_scale", ".weight_scale_2"))
def load_split_param(
name: str,
@@ -2327,6 +2364,7 @@ class HunyuanImage3Model(nn.Module):
num_image_tokens,
first_step,
uncond_cfg_prefill=uncond_cfg_prefill,
gen_timestep_scatter_index=gen_timestep_scatter_index,
)
assert len(set(query_lens)) == 1 and len(set(seq_lens)) == 1, (
"query_lens and seq_lens must be the same for sequence parallel"
@@ -2334,15 +2372,15 @@ class HunyuanImage3Model(nn.Module):
prompt_size = text_hidden_states.shape[1]
shard_image_size = image_hidden_states.shape[1]
if first_step: # [image tokens, last token]
shard_padding_size = shard_image_size * sp_world_size - (num_image_tokens + 1)
else: # [image tokens, last token]
if first_step:
shard_padding_size = shard_image_size * sp_world_size - (origin_query_len - prompt_size)
else:
shard_padding_size = shard_image_size * sp_world_size - num_image_tokens
if first_step:
seq_lens = [prompt_size + shard_image_size + ar_kv_reuse_len for _ in seq_lens]
else:
seq_lens = [x - y for x, y in zip(seq_lens, query_lens)]
seq_lens = [seq_len + shard_image_size - 1 for seq_len in seq_lens]
seq_lens = [seq_len + shard_image_size for seq_len in seq_lens]
query_lens = [prompt_size + shard_image_size for _ in query_lens]
if prompt_size > 0:
@@ -2357,10 +2395,6 @@ class HunyuanImage3Model(nn.Module):
position_ids = image_position_ids
custom_pos_emb = (image_custom_pos_emb_sin, image_custom_pos_emb_cos)
if not first_step:
assert torch.all(~attention_mask[..., -1]), "The last token should not be attended to"
attention_mask = attention_mask[..., :-1] # we attention without last token
if shard_padding_size > 0:
B, H, Q, K = attention_mask.shape
pad = shard_padding_size
@@ -3091,15 +3125,11 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
# Scheduler step (all ranks compute locally in CFG parallel)
latents = self.scheduler.step(pred, t, latents, **_scheduler_step_extra_kwargs, return_dict=False)[0]
if i != len(timesteps) - 1 and should_compute:
offset = model_kwargs.get("ar_kv_reuse_offset", 0)
model_kwargs = self.model._update_model_kwargs_for_generation( # noqa
model_output,
model_kwargs,
)
if input_ids.shape[1] != model_kwargs["position_ids"].shape[1]:
# Select using relative positions
index = model_kwargs["position_ids"] - offset
input_ids = torch.gather(input_ids, 1, index=index)
input_ids = None
attention_mask = model_kwargs.get("attention_mask")
b, _, q_len1, seq_len = attention_mask.shape
query_lens = [q_len1] * b
@@ -1001,7 +1001,7 @@ class HunyuanImage3Pipeline(
if inputs_embeds is not None and past_key_values is None:
model_inputs = {"inputs_embeds": inputs_embeds}
else:
if input_ids.shape[1] != kwargs["position_ids"].shape[1]: # in decode steps
if input_ids is not None and input_ids.shape[1] != kwargs["position_ids"].shape[1]: # in decode steps
input_ids = torch.gather(input_ids, dim=1, index=kwargs["position_ids"])
model_inputs = {"input_ids": input_ids}
@@ -1082,12 +1082,27 @@ class HunyuanImage3Pipeline(
# attention mask
mask_list = []
for attention_mask_i, position_ids_i in zip(
model_kwargs["attention_mask"], updated_model_kwargs["position_ids"]
current_starts = timestep_position_ids.reshape(-1)
max_current_start = int(current_starts.max().item())
for attention_mask_i, position_ids_i, current_start_i in zip(
model_kwargs["attention_mask"], updated_model_kwargs["position_ids"], current_starts
):
mask_list.append(
torch.index_select(attention_mask_i, dim=1, index=position_ids_i.reshape(-1) - offset)
query_mask = torch.index_select(attention_mask_i, dim=1, index=position_ids_i.reshape(-1) - offset)
current_start = int(current_start_i.item())
prefix_mask = torch.index_select(
query_mask,
dim=2,
index=torch.arange(current_start, device=image_mask.device),
)
if current_start < max_current_start:
prefix_pad = query_mask.new_zeros(
query_mask.shape[0],
query_mask.shape[1],
max_current_start - current_start,
)
prefix_mask = torch.cat([prefix_mask, prefix_pad], dim=2)
current_mask = torch.index_select(query_mask, dim=2, index=position_ids_i.reshape(-1))
mask_list.append(torch.cat([prefix_mask, current_mask], dim=2))
attention_mask = torch.stack(mask_list, dim=0)
updated_model_kwargs["attention_mask"] = attention_mask
updated_model_kwargs["gen_timestep_scatter_index"] = model_kwargs["gen_timestep_scatter_index"]
@@ -1219,9 +1234,14 @@ class HunyuanImage3Pipeline(
)
custom_pos_emb = self.get_pos_emb(custom_pos_emb, position_ids)
inputs_embeds = self.model.embed_tokens(input_ids)
bsz, seq_len, n_embd = inputs_embeds.shape
if input_ids is not None:
inputs_embeds = self.model.embed_tokens(input_ids)
bsz, seq_len, n_embd = inputs_embeds.shape
else:
inputs_embeds = None
bsz = images.shape[0] if isinstance(images, torch.Tensor) else len(images)
seq_len = 0
n_embd = self.config.hidden_size
# Instantiate placeholder tokens: <timestep>, <img> for the gen image
if mode == "gen_text":
@@ -1232,6 +1252,7 @@ class HunyuanImage3Pipeline(
token_h, token_w = None, None
else:
if first_step:
assert inputs_embeds is not None
inputs_embeds, token_h, token_w = self.instantiate_vae_image_tokens(
inputs_embeds, images, timestep, image_mask
)
@@ -1253,6 +1274,8 @@ class HunyuanImage3Pipeline(
inputs_embeds = self.instantiate_vit_image_tokens(
inputs_embeds, cond_vit_images, cond_vit_image_mask, vit_kwargs
)
assert inputs_embeds is not None
bsz, seq_len, n_embd = inputs_embeds.shape
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
from vllm.forward_context import set_forward_context
@@ -1291,7 +1314,7 @@ class HunyuanImage3Pipeline(
diffusion_prediction = None
else:
logits = None
hidden_states = hidden_states.to(input_ids.device)
hidden_states = hidden_states.to(inputs_embeds.device)
assert hidden_states.numel() == bsz * seq_len * n_embd, (
f"Shape mismatch: {hidden_states.shape} cannot reshape to ({bsz}, {seq_len}, {n_embd})"
)
@@ -146,6 +146,7 @@ def resolve_stop_token_ids(
task: str = "it2i",
bot_task: str | None | _DefaultBotTask = _DEFAULT_BOT_TASK,
tokenizer: Any | None = None,
image_size: str | None = None,
) -> list[int]:
"""AR stop-token ids for a given (task, bot_task) generation request.
@@ -171,6 +172,14 @@ def resolve_stop_token_ids(
if bot_task not in _BOT_TASK_PRESETS:
raise ValueError(f"Unknown bot_task {bot_task!r}. Choose from: {available_bot_tasks()}")
if task in ("it2i", "t2i"):
need_ratio = image_size is None or image_size == "auto"
if not need_ratio:
end_of_think_id = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["</think>"]
end_of_recaption_id = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["</recaption>"]
if bot_task in ("think_recaption", "recaption"):
return [end_of_recaption_id]
if bot_task == "think":
return [end_of_think_id, end_of_recaption_id]
# Main ratio range: <img_ratio_0> .. <img_ratio_32>.
start = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["<img_ratio_0>"]
end = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["<img_ratio_32>"]
@@ -219,7 +228,7 @@ def build_prompt(
effective_sys_type = sys_type or preset_sys_type
system_prompt = get_system_prompt(effective_sys_type, bot_task, custom_system_prompt)
sys_text = system_prompt or ""
sys_text = system_prompt.strip() if system_prompt is not None else ""
has_image_input = task in ("i2t", "it2i")
if has_image_input:
@@ -288,7 +297,7 @@ def build_prompt_tokens(
)
system_prompt = get_system_prompt(effective_sys_type, bot_task, custom_system_prompt)
sys_text = system_prompt or ""
sys_text = system_prompt.strip() if system_prompt is not None else ""
ids: list[int] = [bos_id]
if sys_text:
@@ -762,7 +762,13 @@ class HunyuanVideo15Transformer3DModel(nn.Module):
encoder_hidden_states = torch.stack(new_encoder_hidden_states)
encoder_attention_mask = torch.stack(new_encoder_attention_mask)
# Create explicit attn_mask for image tokens when SP auto_pad is active.
max_valid_encoder_tokens = int(encoder_attention_mask.sum(dim=1).max().item())
if max_valid_encoder_tokens < encoder_attention_mask.shape[1]:
encoder_hidden_states = encoder_hidden_states[:, :max_valid_encoder_tokens]
encoder_attention_mask = encoder_attention_mask[:, :max_valid_encoder_tokens]
if encoder_attention_mask.all():
encoder_attention_mask = None
ctx = get_forward_context()
hidden_states_mask = None
if ctx.sp_original_seq_len is not None and ctx.sp_padding_size > 0:
@@ -830,9 +836,10 @@ class HunyuanVideo15Transformer3DModel(nn.Module):
for param_name, weight_name, shard_id in stacked_params_mapping:
if weight_name not in original_name:
continue
lookup_name = original_name.replace(weight_name, param_name)
if lookup_name not in params_dict:
break
maybe_lookup_name = original_name.replace(weight_name, param_name)
if maybe_lookup_name not in params_dict:
continue
lookup_name = maybe_lookup_name
param = params_dict[lookup_name]
weight_loader = param.weight_loader
weight_loader(param, loaded_weight, shard_id)
@@ -11,7 +11,6 @@ from typing import Any
import numpy as np
import torch
from diffusers import AutoencoderKLHunyuanVideo15
from diffusers.schedulers.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
from diffusers.utils.torch_utils import randn_tensor
from diffusers.video_processor import VideoProcessor
@@ -20,6 +19,9 @@ from transformers import AutoConfig, ByT5Tokenizer, Qwen2_5_VLTextModel, Qwen2To
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_hunyuan_video_15 import (
DistributedAutoencoderKLHunyuanVideo15,
)
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
@@ -110,7 +112,7 @@ class HunyuanVideo15Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, Diff
t5_config = AutoConfig.from_pretrained(model, subfolder="text_encoder_2", local_files_only=local_files_only)
self.text_encoder_2 = T5EncoderModel(t5_config, prefix="text_encoder_2").to(dtype=dtype, device=self.device)
self.vae = AutoencoderKLHunyuanVideo15.from_pretrained(
self.vae = DistributedAutoencoderKLHunyuanVideo15.from_pretrained(
model, subfolder="vae", torch_dtype=torch.float32, local_files_only=local_files_only
).to(self.device)
@@ -11,7 +11,6 @@ from typing import Any, cast
import numpy as np
import PIL.Image
import torch
from diffusers import AutoencoderKLHunyuanVideo15
from diffusers.schedulers.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
from diffusers.utils.torch_utils import randn_tensor
from diffusers.video_processor import VideoProcessor
@@ -27,6 +26,9 @@ from transformers import (
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_hunyuan_video_15 import (
DistributedAutoencoderKLHunyuanVideo15,
)
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
@@ -139,7 +141,7 @@ class HunyuanVideo15I2VPipeline(
model, subfolder="feature_extractor", local_files_only=local_files_only
)
self.vae = AutoencoderKLHunyuanVideo15.from_pretrained(
self.vae = DistributedAutoencoderKLHunyuanVideo15.from_pretrained(
model, subfolder="vae", torch_dtype=torch.float32, local_files_only=local_files_only
).to(self.device)
@@ -67,13 +67,20 @@ def _make_rms_norm(hidden_size: int, *, eps: float, elementwise_affine: bool) ->
def apply_interleaved_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
cos, sin = freqs
x_real, x_imag = x.unflatten(2, (-1, 2)).unbind(-1) # [B, S, C // 2]
# Concrete pair count instead of -1 keeps SDPA shape static under torch.compile.
x_real, x_imag = x.unflatten(2, (x.shape[2] // 2, 2)).unbind(-1) # [B, S, C // 2]
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(2)
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
return out
def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
def apply_split_rotary_emb(
x: torch.Tensor,
freqs: tuple[torch.Tensor, torch.Tensor],
*,
head_dim: int,
) -> torch.Tensor:
# `head_dim` is plumbed in (not inferred via `-1`) so SDPA shape stays static under torch.compile.
cos, sin = freqs
x_dtype = x.dtype
@@ -83,7 +90,7 @@ def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Ten
# The cos/sin batch dim may only be broadcastable, so take batch size from x
b = x.shape[0]
_, h, t, _ = cos.shape
x = x.reshape(b, t, h, -1).swapaxes(1, 2)
x = x.reshape(b, t, h, head_dim).swapaxes(1, 2)
needs_reshape = True
# Split last dim (2*r) into (d=2, r)
@@ -110,7 +117,7 @@ def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Ten
out = out.reshape(*out.shape[:-2], last)
if needs_reshape:
out = out.swapaxes(1, 2).reshape(b, t, -1)
out = out.swapaxes(1, 2).reshape(b, t, h * head_dim)
out = out.to(dtype=x_dtype)
return out
@@ -488,12 +495,14 @@ class LTX2AudioVideoAttnProcessor:
key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb
)
elif attn.rope_type == "split":
query = apply_split_rotary_emb(query, query_rotary_emb)
key = apply_split_rotary_emb(key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb)
query = apply_split_rotary_emb(query, query_rotary_emb, head_dim=attn.head_dim)
key = apply_split_rotary_emb(
key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb, head_dim=attn.head_dim
)
query = query.unflatten(2, (attn.heads, -1))
key = key.unflatten(2, (attn.heads, -1))
value = value.unflatten(2, (attn.heads, -1))
query = query.unflatten(2, (attn.heads, attn.head_dim))
key = key.unflatten(2, (attn.heads, attn.head_dim))
value = value.unflatten(2, (attn.heads, attn.head_dim))
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
hidden_states = attn.attn(query, key, value, attn_metadata)
@@ -502,7 +511,7 @@ class LTX2AudioVideoAttnProcessor:
# LTX-2.3: per-head gated attention
if attn.to_gate_logits is not None:
hidden_states = hidden_states.unflatten(2, (attn.heads, -1)) # [B, T, H, D]
hidden_states = hidden_states.unflatten(2, (attn.heads, attn.head_dim)) # [B, T, H, D]
# 2.0 * sigmoid so zero-init gates produce 1.0 (identity)
gates = 2.0 * torch.sigmoid(gate_logits) # [B, T, H]
hidden_states = hidden_states * gates.unsqueeze(-1)
@@ -1391,9 +1400,11 @@ class LTX2AudioVideoRotaryPosEmbed(nn.Module):
# Reshape freqs to be compatible with multi-head attention
b = cos_freq.shape[0]
t = cos_freq.shape[1]
# Concrete per-head dim instead of -1 — see apply_split_rotary_emb
r = self.dim // self.num_attention_heads // 2
cos_freq = cos_freq.reshape(b, t, self.num_attention_heads, -1)
sin_freq = sin_freq.reshape(b, t, self.num_attention_heads, -1)
cos_freq = cos_freq.reshape(b, t, self.num_attention_heads, r)
sin_freq = sin_freq.reshape(b, t, self.num_attention_heads, r)
cos_freqs = torch.swapaxes(cos_freq, 1, 2) # (B,H,T,D//2)
sin_freqs = torch.swapaxes(sin_freq, 1, 2) # (B,H,T,D//2)
@@ -1939,10 +1950,6 @@ class LTX2VideoTransformer3DModel(nn.Module):
# 5. Run transformer blocks
for block in self.transformer_blocks:
block_kwargs = {
"hidden_states": hidden_states,
"audio_hidden_states": audio_hidden_states,
"encoder_hidden_states": encoder_hidden_states,
"audio_encoder_hidden_states": audio_encoder_hidden_states,
"temb": temb,
"temb_audio": temb_audio,
"temb_ca_scale_shift": video_cross_attn_scale_shift,
@@ -1958,11 +1965,27 @@ class LTX2VideoTransformer3DModel(nn.Module):
"encoder_attention_mask": encoder_attention_mask,
"audio_encoder_attention_mask": audio_encoder_attention_mask,
}
# NOTE: We intentionally pass the first 4 args here positionally,
# because CacheDiT expects the first 2 args to be hidden_states
# and encoder_hidden_states, so passing them as kwargs will cause
# positional / keywords arg collisions.
if torch.is_grad_enabled() and self.gradient_checkpointing:
hidden_states, audio_hidden_states = self._gradient_checkpointing_func(block, **block_kwargs)
hidden_states, audio_hidden_states = self._gradient_checkpointing_func(
block,
hidden_states,
audio_hidden_states,
encoder_hidden_states,
audio_encoder_hidden_states,
**block_kwargs,
)
else:
hidden_states, audio_hidden_states = block(**block_kwargs)
hidden_states, audio_hidden_states = block(
hidden_states,
audio_hidden_states,
encoder_hidden_states,
audio_encoder_hidden_states,
**block_kwargs,
)
# 6. Output layers (including unpatchification)
scale_shift_values = self.scale_shift_table[None, None] + embedded_timestep[:, :, None]
shift, scale = scale_shift_values[:, :, 0], scale_shift_values[:, :, 1]
@@ -157,6 +157,9 @@ class _VideoAudioScheduler:
class LTX2Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
# Audio is diffused jointly with video; warmup must size audio tokens.
dummy_run_num_frames = 2
def __init__(
self,
*,
@@ -1118,6 +1121,8 @@ class LTX2Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
class LTX2TwoStagesPipeline(nn.Module, SupportsComponentDiscovery):
"""LTX2TwoStagesPipeline is for two stages image to video generation"""
dummy_run_num_frames = 2
_dit_modules: ClassVar[list[str]] = ["pipe.transformer"]
_encoder_modules: ClassVar[list[str]] = ["pipe.text_encoder"]
_vae_modules: ClassVar[list[str]] = ["pipe.vae", "pipe.audio_vae"]
@@ -37,6 +37,12 @@ from vllm.logger import init_logger
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
from vllm_omni.diffusion.distributed.parallel_state import (
get_cfg_group,
get_classifier_free_guidance_rank,
get_classifier_free_guidance_world_size,
)
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
@@ -44,6 +50,7 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
from .pipeline_ltx2 import (
_get_prompt_field,
_VideoAudioScheduler,
calculate_shift,
create_transformer_from_config,
load_transformer_config,
@@ -104,7 +111,7 @@ def get_ltx2_post_process_func(od_config: OmniDiffusionConfig):
return post_process_func
class LTX23Pipeline(nn.Module, ProgressBarMixin):
class LTX23Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
"""Fully independent LTX-2.3 pipeline.
Key differences from LTX2Pipeline:
@@ -115,6 +122,9 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
- CPU offloading: text encoder, connectors, VAE, vocoder stay on CPU
"""
# Audio is diffused jointly with video; warmup must size audio tokens.
dummy_run_num_frames = 2
def __init__(
self,
*,
@@ -445,6 +455,26 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
def _unpad_audio_latents(latents: torch.Tensor, num_frames: int) -> torch.Tensor:
return latents[:, :num_frames]
@staticmethod
def _get_sp_padded_audio_latent_length(audio_latent_length: int, sp_size: int) -> int:
if sp_size > 1:
audio_latent_length += (sp_size - (audio_latent_length % sp_size)) % sp_size
return audio_latent_length
def _resolve_audio_latent_length(self, audio_latent_length: int, audio_latents: torch.Tensor | None) -> int:
if audio_latents is None or audio_latents.ndim != 4:
return audio_latent_length
provided_latent_length = audio_latents.shape[2]
sp_size = getattr(self.od_config.parallel_config, "sequence_parallel_size", 1) or 1
padded_latent_length = self._get_sp_padded_audio_latent_length(audio_latent_length, int(sp_size))
# Keep requested duration semantics when callers pass 4D latents that
# are already padded for SP; other 4D lengths retain shape inference.
if provided_latent_length in {audio_latent_length, padded_latent_length}:
return audio_latent_length
return provided_latent_length
# ------------------------------------------------------------------
# Latent preparation
# ------------------------------------------------------------------
@@ -497,9 +527,11 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
latents: torch.Tensor | None = None,
) -> tuple[torch.Tensor, int, int]:
original_latent_length = audio_latent_length
padded_latent_length = original_latent_length
latent_mel_bins = num_mel_bins // self.audio_vae_mel_compression_ratio
sp_size = getattr(self.od_config.parallel_config, "sequence_parallel_size", 1) or 1
padded_latent_length = self._get_sp_padded_audio_latent_length(original_latent_length, int(sp_size))
if latents is not None:
if latents.ndim == 4:
latents = self._pack_audio_latents(latents)
@@ -508,9 +540,32 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
latents = self._normalize_audio_latents(latents, self.audio_vae.latents_mean, self.audio_vae.latents_std)
noise = randn_tensor(latents.shape, generator=generator, device=latents.device, dtype=latents.dtype)
latents = noise_scale * noise + (1 - noise_scale) * latents
if latents.shape[1] not in {original_latent_length, padded_latent_length}:
raise ValueError(
"Provided `audio_latents` has incompatible audio frame count "
f"{latents.shape[1]}; expected {original_latent_length} or {padded_latent_length}."
)
if latents.shape[1] == original_latent_length and padded_latent_length > original_latent_length:
padding = torch.zeros(
latents.shape[0],
padded_latent_length - original_latent_length,
latents.shape[2],
dtype=latents.dtype,
device=latents.device,
)
latents = torch.cat([latents, padding], dim=1)
return latents.to(device=device, dtype=dtype), original_latent_length, padded_latent_length
shape = (batch_size, num_channels_latents, padded_latent_length, latent_mel_bins)
if isinstance(generator, list) and len(generator) != batch_size:
raise ValueError(
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
)
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
latents = self._pack_audio_latents(latents)
return latents, original_latent_length, padded_latent_length
@@ -593,6 +648,121 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
return cache_context(context_name)
return nullcontext()
# ------------------------------------------------------------------
# CFG helpers
# ------------------------------------------------------------------
@staticmethod
def _combine_x0_space_cfg(
sample: torch.Tensor,
positive_noise_pred: torch.Tensor,
negative_noise_pred: torch.Tensor,
sigma: torch.Tensor,
guidance_scale: float,
) -> torch.Tensor:
x0_cond = sample - positive_noise_pred * sigma
x0_uncond = sample - negative_noise_pred * sigma
x0_guided = x0_cond + (guidance_scale - 1) * (x0_cond - x0_uncond)
return (sample - x0_guided) / sigma
def predict_noise(self, **kwargs):
with self._transformer_cache_context("cond_uncond"):
noise_pred_video, noise_pred_audio = self.transformer(**kwargs)
return noise_pred_video.float(), noise_pred_audio.float()
def combine_cfg_noise(
self,
positive_noise_pred,
negative_noise_pred,
true_cfg_scale,
cfg_normalize=False,
*,
video_latents: torch.Tensor | None = None,
audio_latents: torch.Tensor | None = None,
video_sigma: torch.Tensor | None = None,
audio_sigma: torch.Tensor | None = None,
):
if video_latents is None or audio_latents is None or video_sigma is None or audio_sigma is None:
raise ValueError("LTX23Pipeline applies CFG in x0-space and requires video/audio latents and sigmas.")
video_pos, audio_pos = positive_noise_pred
video_neg, audio_neg = negative_noise_pred
video_combined = self._combine_x0_space_cfg(
video_latents,
video_pos,
video_neg,
video_sigma,
true_cfg_scale,
)
audio_combined = self._combine_x0_space_cfg(
audio_latents,
audio_pos,
audio_neg,
audio_sigma,
true_cfg_scale,
)
if cfg_normalize:
video_combined = self.cfg_normalize_function(video_pos, video_combined)
audio_combined = self.cfg_normalize_function(audio_pos, audio_combined)
return video_combined, audio_combined
def predict_noise_with_parallel_cfg(
self,
true_cfg_scale: float,
positive_kwargs: dict[str, Any],
negative_kwargs: dict[str, Any],
cfg_normalize: bool = True,
output_slice: int | None = None,
*,
video_latents: torch.Tensor | None = None,
audio_latents: torch.Tensor | None = None,
video_sigma: torch.Tensor | None = None,
audio_sigma: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
def maybe_slice(pred: tuple[torch.Tensor, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
if output_slice is None:
return pred
return pred[0][:, :output_slice], pred[1][:, :output_slice]
cfg_world_size = get_classifier_free_guidance_world_size()
if cfg_world_size != 2:
raise ValueError(f"LTX23Pipeline parallel CFG requires cfg_parallel_size 2, but got {cfg_world_size}.")
cfg_group = get_cfg_group()
cfg_rank = get_classifier_free_guidance_rank()
branch_kwargs = positive_kwargs if cfg_rank == 0 else negative_kwargs
local_video_pred, local_audio_pred = maybe_slice(self.predict_noise(**branch_kwargs))
gathered_video = cfg_group.all_gather(local_video_pred, separate_tensors=True)
gathered_audio = cfg_group.all_gather(local_audio_pred, separate_tensors=True)
positive_noise_pred = (gathered_video[0], gathered_audio[0])
negative_noise_pred = (gathered_video[1], gathered_audio[1])
return self.combine_cfg_noise(
positive_noise_pred,
negative_noise_pred,
true_cfg_scale,
cfg_normalize,
video_latents=video_latents,
audio_latents=audio_latents,
video_sigma=video_sigma,
audio_sigma=audio_sigma,
)
def _synchronize_cfg_parallel_step_output(
self,
latents: tuple[torch.Tensor, torch.Tensor],
do_true_cfg: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
if not (do_true_cfg and get_classifier_free_guidance_world_size() > 1):
return latents
latents = tuple(tensor.contiguous() for tensor in latents)
device = next((tensor.device for tensor in latents if tensor.is_cuda), None)
if device is not None:
torch.cuda.current_stream(device).synchronize()
return latents
# ------------------------------------------------------------------
# Forward pass
# ------------------------------------------------------------------
@@ -711,6 +881,12 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
self._attention_kwargs = attention_kwargs
self._interrupt = False
self._current_timestep = None
cfg_world_size = get_classifier_free_guidance_world_size()
if self.do_classifier_free_guidance and cfg_world_size not in (1, 2):
raise ValueError(
f"LTX23Pipeline supports CFG parallelism with cfg_parallel_size 1 or 2, but got {cfg_world_size}."
)
cfg_parallel_ready = self.do_classifier_free_guidance and cfg_world_size > 1
if prompt is not None and isinstance(prompt, str):
batch_size = 1
@@ -757,6 +933,21 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
if torch.cuda.is_available():
torch.accelerator.empty_cache()
positive_connector_prompt_embeds = connector_prompt_embeds
positive_connector_audio_prompt_embeds = connector_audio_prompt_embeds
positive_connector_attention_mask = connector_attention_mask
negative_connector_prompt_embeds = None
negative_connector_audio_prompt_embeds = None
negative_connector_attention_mask = None
if self.do_classifier_free_guidance:
split_batch = batch_size * num_videos_per_prompt
negative_connector_prompt_embeds = connector_prompt_embeds[:split_batch]
positive_connector_prompt_embeds = connector_prompt_embeds[split_batch:]
negative_connector_audio_prompt_embeds = connector_audio_prompt_embeds[:split_batch]
positive_connector_audio_prompt_embeds = connector_audio_prompt_embeds[split_batch:]
negative_connector_attention_mask = connector_attention_mask[:split_batch]
positive_connector_attention_mask = connector_attention_mask[split_batch:]
# ---- Prepare latents ----
latent_num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
latent_height = height // self.vae_spatial_compression_ratio
@@ -783,8 +974,7 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
self.audio_sampling_rate / self.audio_hop_length / float(self.audio_vae_temporal_compression_ratio)
)
audio_num_frames = round(duration_s * audio_latents_per_second)
if audio_latents is not None and audio_latents.ndim == 4:
_, _, audio_num_frames, _ = audio_latents.shape
audio_num_frames = self._resolve_audio_latent_length(audio_num_frames, audio_latents)
num_mel_bins = self.audio_vae.config.mel_bins if self.audio_vae is not None else 64
latent_mel_bins = num_mel_bins // self.audio_vae_mel_compression_ratio
@@ -813,6 +1003,7 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
self.scheduler.config.get("max_shift", 2.05),
)
audio_scheduler = copy.deepcopy(self.scheduler)
video_audio_scheduler = _VideoAudioScheduler(self.scheduler, audio_scheduler)
_ = retrieve_timesteps(audio_scheduler, num_inference_steps, device, timesteps, sigmas=sigmas, mu=mu)
timesteps, num_inference_steps = retrieve_timesteps(
self.scheduler,
@@ -839,9 +1030,9 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
audio_latents.device,
)
# ---- CFG: duplicate coords for batch=2 ----
# ---- CFG: duplicate coords for single-rank batch=2 CFG ----
# Connector outputs are already batch=2 (neg+pos concatenated before connector call)
if self.do_classifier_free_guidance:
if self.do_classifier_free_guidance and not cfg_parallel_ready:
video_coords = video_coords.repeat((2,) + (1,) * (video_coords.ndim - 1))
audio_coords = audio_coords.repeat((2,) + (1,) * (audio_coords.ndim - 1))
@@ -856,60 +1047,112 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
self._current_timestep = t
# Duplicate latents for CFG (uncond + cond)
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
latent_model_input = latent_model_input.to(connector_prompt_embeds.dtype)
audio_latent_model_input = (
torch.cat([audio_latents] * 2) if self.do_classifier_free_guidance else audio_latents
)
audio_latent_model_input = audio_latent_model_input.to(connector_prompt_embeds.dtype)
ts = t.expand(latent_model_input.shape[0])
with self._transformer_cache_context("cond_uncond"):
noise_pred_video, noise_pred_audio = self.transformer(
hidden_states=latent_model_input,
audio_hidden_states=audio_latent_model_input,
encoder_hidden_states=connector_prompt_embeds,
audio_encoder_hidden_states=connector_audio_prompt_embeds,
timestep=ts,
sigma=ts, # LTX-2.3: sigma for prompt_adaln
encoder_attention_mask=connector_attention_mask,
audio_encoder_attention_mask=connector_attention_mask,
num_frames=latent_num_frames,
height=latent_height,
width=latent_width,
fps=frame_rate,
audio_num_frames=padded_audio_num_frames,
video_coords=video_coords,
audio_coords=audio_coords,
attention_kwargs=attention_kwargs,
return_dict=False,
if cfg_parallel_ready:
latent_model_input = latents.to(positive_connector_prompt_embeds.dtype)
audio_latent_model_input = audio_latents.to(positive_connector_prompt_embeds.dtype)
ts = t.expand(latent_model_input.shape[0])
positive_kwargs = {
"hidden_states": latent_model_input,
"audio_hidden_states": audio_latent_model_input,
"encoder_hidden_states": positive_connector_prompt_embeds,
"audio_encoder_hidden_states": positive_connector_audio_prompt_embeds,
"timestep": ts,
"sigma": ts,
"encoder_attention_mask": positive_connector_attention_mask,
"audio_encoder_attention_mask": positive_connector_attention_mask,
"num_frames": latent_num_frames,
"height": latent_height,
"width": latent_width,
"fps": frame_rate,
"audio_num_frames": padded_audio_num_frames,
"video_coords": video_coords,
"audio_coords": audio_coords,
"attention_kwargs": attention_kwargs,
"return_dict": False,
}
negative_kwargs = {
**positive_kwargs,
"encoder_hidden_states": negative_connector_prompt_embeds,
"audio_encoder_hidden_states": negative_connector_audio_prompt_embeds,
"encoder_attention_mask": negative_connector_attention_mask,
"audio_encoder_attention_mask": negative_connector_attention_mask,
}
noise_pred_video, noise_pred_audio = self.predict_noise_with_parallel_cfg(
true_cfg_scale=guidance_scale,
positive_kwargs=positive_kwargs,
negative_kwargs=negative_kwargs,
cfg_normalize=False,
video_latents=latents,
audio_latents=audio_latents,
video_sigma=self.scheduler.sigmas[i],
audio_sigma=audio_scheduler.sigmas[i],
)
noise_pred_video = noise_pred_video.float()
noise_pred_audio = noise_pred_audio.float()
latents, audio_latents = self.scheduler_step_maybe_with_cfg(
(noise_pred_video, noise_pred_audio),
(t, t),
(latents, audio_latents),
do_true_cfg=self.do_classifier_free_guidance,
per_request_scheduler=video_audio_scheduler,
)
latents, audio_latents = self._synchronize_cfg_parallel_step_output(
(latents, audio_latents),
do_true_cfg=self.do_classifier_free_guidance,
)
else:
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
latent_model_input = latent_model_input.to(connector_prompt_embeds.dtype)
audio_latent_model_input = (
torch.cat([audio_latents] * 2) if self.do_classifier_free_guidance else audio_latents
)
audio_latent_model_input = audio_latent_model_input.to(connector_prompt_embeds.dtype)
ts = t.expand(latent_model_input.shape[0])
# CFG in x0-space (delta formulation matching diffusers)
if self.do_classifier_free_guidance:
noise_pred_video_uncond, noise_pred_video_cond = noise_pred_video.chunk(2)
# Convert velocity to x0: x0 = sample - velocity * sigma
x0_video_cond = latents - noise_pred_video_cond * self.scheduler.sigmas[i]
x0_video_uncond = latents - noise_pred_video_uncond * self.scheduler.sigmas[i]
video_cfg_delta = (guidance_scale - 1) * (x0_video_cond - x0_video_uncond)
x0_video_guided = x0_video_cond + video_cfg_delta
with self._transformer_cache_context("cond_uncond"):
noise_pred_video, noise_pred_audio = self.transformer(
hidden_states=latent_model_input,
audio_hidden_states=audio_latent_model_input,
encoder_hidden_states=connector_prompt_embeds,
audio_encoder_hidden_states=connector_audio_prompt_embeds,
timestep=ts,
sigma=ts, # LTX-2.3: sigma for prompt_adaln
encoder_attention_mask=connector_attention_mask,
audio_encoder_attention_mask=connector_attention_mask,
num_frames=latent_num_frames,
height=latent_height,
width=latent_width,
fps=frame_rate,
audio_num_frames=padded_audio_num_frames,
video_coords=video_coords,
audio_coords=audio_coords,
attention_kwargs=attention_kwargs,
return_dict=False,
)
noise_pred_audio_uncond, noise_pred_audio_cond = noise_pred_audio.chunk(2)
x0_audio_cond = audio_latents - noise_pred_audio_cond * audio_scheduler.sigmas[i]
x0_audio_uncond = audio_latents - noise_pred_audio_uncond * audio_scheduler.sigmas[i]
audio_cfg_delta = (guidance_scale - 1) * (x0_audio_cond - x0_audio_uncond)
x0_audio_guided = x0_audio_cond + audio_cfg_delta
noise_pred_video = noise_pred_video.float()
noise_pred_audio = noise_pred_audio.float()
# Convert x0 back to velocity: v = (sample - x0) / sigma
noise_pred_video = (latents - x0_video_guided) / self.scheduler.sigmas[i]
noise_pred_audio = (audio_latents - x0_audio_guided) / audio_scheduler.sigmas[i]
if self.do_classifier_free_guidance:
noise_pred_video_uncond, noise_pred_video_cond = noise_pred_video.chunk(2)
noise_pred_video = self._combine_x0_space_cfg(
latents,
noise_pred_video_cond,
noise_pred_video_uncond,
self.scheduler.sigmas[i],
guidance_scale,
)
latents = self.scheduler.step(noise_pred_video, t, latents, return_dict=False)[0]
audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0]
noise_pred_audio_uncond, noise_pred_audio_cond = noise_pred_audio.chunk(2)
noise_pred_audio = self._combine_x0_space_cfg(
audio_latents,
noise_pred_audio_cond,
noise_pred_audio_uncond,
audio_scheduler.sigmas[i],
guidance_scale,
)
latents = self.scheduler.step(noise_pred_video, t, latents, return_dict=False)[0]
audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0]
pbar.update()
@@ -735,6 +735,7 @@ class LTX2ImageToVideoTwoStagesPipeline(nn.Module, SupportsComponentDiscovery):
"""LTXImageToVideoTwoStagesPipeline is for two stages image to video generation"""
support_image_input = True
dummy_run_num_frames = 2
_dit_modules: ClassVar[list[str]] = ["pipe.transformer"]
_encoder_modules: ClassVar[list[str]] = ["pipe.text_encoder"]
@@ -2130,6 +2130,28 @@ class MagiHumanPipeline(nn.Module, ProgressBarMixin, DiffusionPipelineProfilerMi
return resample(audio_np, target_len)
def encode_prompt(
self,
prompt: str,
target_length: int | None = None,
) -> tuple[torch.Tensor, int]:
"""Encode *prompt* with the T5-Gemma text encoder and pad to fixed length.
This is the single text-encoder entrypoint so the runner-level
prompt-embedding cache (see
``vllm_omni/diffusion/cache/prompt_embed_cache.py``) can transparently
memoize results when the same prompt is submitted repeatedly.
Returns:
``(context, original_context_len)`` matching
:func:`_get_padded_t5_gemma_embedding`.
"""
return _get_padded_t5_gemma_embedding(
prompt,
self.text_encoder,
target_length if target_length is not None else self.t5_gemma_target_length,
)
@torch.inference_mode()
def forward(
self,
@@ -2200,11 +2222,7 @@ class MagiHumanPipeline(nn.Module, ProgressBarMixin, DiffusionPipelineProfilerMi
device=device,
)
context, original_context_len = _get_padded_t5_gemma_embedding(
prompt,
self.text_encoder,
self.t5_gemma_target_length,
)
context, original_context_len = self.encode_prompt(prompt)
if image_path is not None:
br_image = self._encode_image(load_image(image_path), br_height, br_width)
@@ -0,0 +1,20 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 The vLLM-Omni team.
from .byte5_encoder import MingByT5Encoder
from .condition_encoder import MingConditionEncoder
from .ming_zimage_transformer import MingZImageTransformer2DModel
from .pipeline_ming_imagegen import (
MingImagePipeline,
get_ming_image_post_process_func,
)
from .t5_block_mapper import T5EncoderBlockByT5Mapper
__all__ = [
"MingByT5Encoder",
"MingConditionEncoder",
"MingImagePipeline",
"MingZImageTransformer2DModel",
"T5EncoderBlockByT5Mapper",
"get_ming_image_post_process_func",
]
@@ -0,0 +1,223 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 The vLLM-Omni team.
"""ByT5 glyph/text encoder for Ming-flash-omni-2.0 image generation.
Ported from Ming's ``load_byte5_and_byte5_tokenizer`` +
``T5EncoderBlockByT5Mapper`` + ``get_condition_embeds_for_image_gen`` byte5
branch. The released checkpoint's byte5 weights were trained with font/color
special tokens, so we replicate that vocabulary extension before loading —
otherwise ``byte5_model.pt`` would shape-mismatch at the embedding layer.
Typical forward: takes a list of user-supplied prompt strings (possibly with
``<cn-font-N>`` / ``<color-N>`` markers), returns ``[B, byte5_max_length,
diffusion_c_input_dim]`` features ready to be concatenated onto cap_feats
along the sequence dimension.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
from types import SimpleNamespace
import torch
import torch.nn as nn
from transformers import AutoTokenizer, T5ForConditionalGeneration
from vllm_omni.diffusion.models.ming_flash_omni.t5_block_mapper import (
T5EncoderBlockByT5Mapper,
)
logger = logging.getLogger(__name__)
def _add_multilingual_special_tokens(
tokenizer,
text_encoder: nn.Module,
font_ann_path: Path,
color_ann_path: Path,
add_font: bool,
add_color: bool,
add_align: bool = False,
) -> None:
"""Extend the byte5 vocab with per-language font + color markers.
Mirrors ``add_special_token_multilingual`` in Ming's bizgen utils. The token
set must match the one the checkpoint was trained with, otherwise the
resized embedding table shape won't line up with the shipped weights.
"""
idx_font_dict = json.loads(font_ann_path.read_text())
idx_color_dict = json.loads(color_ann_path.read_text())
font_tokens: list[str] = []
for font_code in idx_font_dict:
prefix = font_code[:3]
if prefix in ("cn-", "en-", "jp-", "kr-"):
font_tokens.append(f"<{prefix}font-{idx_font_dict[font_code]}>")
else:
font_tokens.append(f"<font-{idx_font_dict[font_code]}>")
color_tokens = [f"<color-{i}>" for i in range(len(idx_color_dict))]
align_tokens = [f"<align-{i}>" for i in range(3)]
extra: list[str] = []
if add_color:
extra += color_tokens
if add_font:
extra += font_tokens
if add_align:
extra += align_tokens
tokenizer.add_tokens(extra, special_tokens=True)
text_encoder.resize_token_embeddings(len(tokenizer))
class MingByT5Encoder(nn.Module):
"""Bundles byte5 tokenizer + T5 encoder + T5EncoderBlockByT5Mapper.
Build with ``MingByT5Encoder.from_checkpoint(<model>/byte5)`` when the
checkpoint ships byte5 weights; otherwise callers can skip this and the
pipeline falls back to no-byte5 conditioning.
"""
def __init__(
self,
tokenizer,
text_encoder: nn.Module,
mapper: T5EncoderBlockByT5Mapper,
max_length: int,
) -> None:
super().__init__()
self.tokenizer = tokenizer
self.text_encoder = text_encoder
self.mapper = mapper
self.max_length = max_length
@classmethod
def from_checkpoint(
cls,
byte5_dir: Path,
*,
device: torch.device,
dtype: torch.dtype,
) -> MingByT5Encoder:
# Wrap the whole load in fork_rng so any nn.init.normal_ inside
# T5ForConditionalGeneration.from_pretrained / vocab-resize cannot
# advance the default CPU/CUDA generator state. Without this, the
# diffusion pipeline's seeded noise becomes order-dependent across
# requests (same-seed replays diverge).
cuda_devs = list(range(torch.accelerator.device_count())) if torch.cuda.is_available() else []
with torch.random.fork_rng(devices=cuda_devs, enabled=True):
return cls._from_checkpoint_impl(byte5_dir, device=device, dtype=dtype)
@classmethod
def _from_checkpoint_impl(
cls,
byte5_dir: Path,
*,
device: torch.device,
dtype: torch.dtype,
) -> MingByT5Encoder:
byte5_dir = Path(byte5_dir)
# Ming checkpoint uses ``byt5`` (no 'e') in filenames and JSON keys
# variable names below keep the ``byte5_`` spelling for readability.
cfg_path = byte5_dir / "byt5.json"
cfg_raw = json.loads(cfg_path.read_text())
cfg = SimpleNamespace(**cfg_raw)
byte5_config = cfg.byt5_config
mapper_config = cfg.byt5_mapper_config
max_length = int(cfg.byt5_max_length)
# ---- Tokenizer + T5 encoder (base).
ckpt_key = byte5_config.get("byt5_ckpt_path")
byte5_ckpt_path = byte5_dir / ckpt_key.lstrip("./")
tokenizer = AutoTokenizer.from_pretrained(byte5_ckpt_path, local_files_only=True)
text_encoder = T5ForConditionalGeneration.from_pretrained(byte5_ckpt_path, local_files_only=True).get_encoder()
# ---- Extend vocab with font/color markers so the shipped weights load.
if byte5_config.get("special_token"):
if not byte5_config.get("multilingual", True):
raise NotImplementedError(
"Non-multilingual byte5 vocab extension is not ported; "
"the released Ming checkpoint uses multilingual=True."
)
_add_multilingual_special_tokens(
tokenizer,
text_encoder,
font_ann_path=byte5_dir / byte5_config["font_ann_path"].lstrip("./"),
color_ann_path=byte5_dir / byte5_config["color_ann_path"].lstrip("./"),
add_font=bool(byte5_config.get("font_special_token")),
add_color=bool(byte5_config.get("color_special_token")),
)
# ---- Load byt5 text-encoder weights (base.pt wraps the backbone in a
# trainable-module container; byt5_model.pt has the top-level encoder
# state). Follow Ming's two-step load.
base_state = torch.load(byte5_dir / "byt5_model" / "base.pt", map_location="cpu", weights_only=False)
prefix = "module.text_tower.encoder."
base_filtered = {
name[len(prefix) :]: state for name, state in base_state["state_dict"].items() if name.startswith(prefix)
}
text_encoder.load_state_dict(base_filtered, strict=True)
del base_state, base_filtered
encoder_state = torch.load(byte5_dir / "byt5_model" / "byt5_model.pt", map_location="cpu", weights_only=False)
text_encoder.load_state_dict(encoder_state)
del encoder_state
text_encoder.to(device=device, dtype=dtype).eval()
# ---- Mapper.
mapper = T5EncoderBlockByT5Mapper(
byte5_config=text_encoder.config,
num_layers=int(mapper_config["num_layers"]),
sdxl_channels=int(mapper_config["sdxl_channels"]),
)
mapper_state = torch.load(byte5_dir / "byt5_mapper" / "byt5_mapper.pt", map_location="cpu", weights_only=False)
# mapper now uses vllm-omni TP-aware T5 layers (fused qkv_proj / wi);
mapper.load_weights(mapper_state.items())
del mapper_state
mapper.to(device=device, dtype=dtype).eval()
logger.info(
"[MingByT5Encoder] ready: d_model=%d mapper_layers=%d sdxl_channels=%d max_length=%d vocab=%d",
text_encoder.config.d_model,
mapper_config["num_layers"],
mapper_config["sdxl_channels"],
max_length,
len(tokenizer),
)
return cls(tokenizer, text_encoder, mapper, max_length)
@torch.inference_mode()
def forward(self, texts: list[str]) -> torch.Tensor:
"""Tokenize → T5 encode → mapper; masks out padded positions.
Returns ``[B, max_length, sdxl_channels]``. Padded positions are zeroed
so the downstream ``torch.cat`` with cap_feats doesn't inject garbage.
"""
device = next(self.text_encoder.parameters()).device
dtype = next(self.text_encoder.parameters()).dtype
tokens = self.tokenizer(
texts,
padding="max_length",
max_length=self.max_length,
truncation=True,
add_special_tokens=True,
return_tensors="pt",
)
input_ids = tokens.input_ids.to(device)
attention_mask = tokens.attention_mask.to(device)
encoder_out = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask.float(),
)
hidden_states = encoder_out[0]
feats = self.mapper(hidden_states, attention_mask)
feats = feats * attention_mask.unsqueeze(-1).to(dtype=feats.dtype)
return feats.to(dtype=dtype)
__all__ = ["MingByT5Encoder"]
@@ -0,0 +1,373 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 The vLLM-Omni team.
#
# Adapted from Ming repository (inclusionAI/Ming) — the ``get_condition_embeds
# _for_image_gen`` path in modeling_bailingmm2.py.
"""Ming-flash-omni-2.0 condition encoder for image generation.
Pipeline (runs inside the imagegen stage):
thinker hidden states at query-token positions [B, N, 4096]
│
▼ proj_in (Linear, bias=True)
[B, N, 1536]
│
▼ Qwen2ForCausalLM connector (is_causal=False)
loaded from <checkpoint>/connector/
[B, N, 1536]
│
▼ proj_out (Linear, bias=True)
[B, N, 2560]
│
▼ F.normalize(dim=-1) × 1000 (text_encoder_norm)
[B, N, 2560]
│
▼
cap_feats consumed by ZImageTransformer2DModel
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
import torch
import torch.nn as nn
from vllm_omni.transformers_utils.configs.ming_flash_omni import MingImageGenConfig
logger = logging.getLogger(__name__)
class MingConditionEncoder(nn.Module):
"""Wraps a Qwen2 connector + norm/projection, producing DiT condition embeds.
The connector is a ``Qwen2ForCausalLM`` loaded from the ``connector/``
subfolder of the Ming checkpoint. We run its base model in a non-causal
(bidirectional) mode, because the connector is used as an encoder over the
pre-baked query-token hidden states, not as an autoregressive decoder.
Args:
image_gen_config: ``MingImageGenConfig`` from ``MingFlashOmniConfig``.
thinker_hidden_size: Hidden size of the thinker (BailingMoeV2) model.
Used to build a ``proj_in`` layer when the connector embedding
dim differs. For the released checkpoint this is 4096.
device: Placement for the module.
dtype: Parameter dtype (typically bfloat16 / float16).
"""
def __init__(
self,
image_gen_config: MingImageGenConfig,
*,
thinker_hidden_size: int = 4096,
device: torch.device | str | None = None,
dtype: torch.dtype | None = None,
) -> 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
# Populated lazily by ``load_from_checkpoint`` to keep this module
# cheap to construct (useful for dummy-init paths and unit tests).
self.connector: nn.Module | None = None
self.connector_hidden_size: int | None = None
self.proj_in: nn.Module = nn.Identity()
self.proj_out: nn.Module = nn.Identity()
self.norm: nn.Module = nn.Identity()
# ------------------------------------------------------------------
# Weight loading
# ------------------------------------------------------------------
def load_from_checkpoint(self, model_path: str | Path) -> None:
"""Load the Qwen2 connector + optional projection/norm weights.
This uses HF transformers directly (not vllm's weight loader) because
the connector is small (~1.5B params) and only runs once per request
as an encoder — vllm's distributed loading machinery is overkill.
"""
from transformers import AutoConfig, Qwen2ForCausalLM
model_path = Path(model_path)
connector_path = model_path / self.config.connector_subfolder
logger.info("[MingConditionEncoder] loading connector from %s", connector_path)
connector_cfg = AutoConfig.from_pretrained(connector_path, trust_remote_code=True, local_files_only=True)
# Disable causal masking: the connector is used as a bidirectional
# encoder over query-token hidden states in image-gen mode.
connector_cfg.is_decoder = False
self.connector_hidden_size = int(connector_cfg.hidden_size)
logger.info(
"[MingConditionEncoder] connector hidden_size=%d, layers=%d",
self.connector_hidden_size,
getattr(connector_cfg, "num_hidden_layers", -1),
)
connector = Qwen2ForCausalLM.from_pretrained(
connector_path,
config=connector_cfg,
torch_dtype=self._target_dtype,
local_files_only=True,
)
# Force bidirectional attention in every self-attn module. Qwen2 layers
# do not branch on ``is_causal`` directly, so we monkey-patch the flag
# on each attention block (defensive — some transformers versions read
# ``self_attn.is_causal`` in forward).
patched = 0
for module in connector.modules():
if hasattr(module, "is_causal"):
module.is_causal = False
patched += 1
logger.info("[MingConditionEncoder] disabled is_causal on %d sub-modules", patched)
# We only need the base encoder (no LM head).
base = getattr(connector, "model", connector)
self.connector = base
# proj_in: align thinker_hidden_size -> connector_hidden_size.
# Observed layout of mlp/ on the released checkpoint
# (inclusionAI/Ming-flash-omni-2.0):
# proj_in.{weight,bias} : Linear(4096 -> 1536)
# proj_out.{weight,bias} : Linear(1536 -> 2560)
# query_tokens_dict.16x16 : learnable tokens consumed on the thinker
# side (NOT loaded here).
logger.info(
"[MingConditionEncoder] adding proj_in: %d -> %d (bias=True)",
self.thinker_hidden_size,
self.connector_hidden_size,
)
self.proj_in = nn.Linear(self.thinker_hidden_size, self.connector_hidden_size, bias=True)
# NOTE: ``text_encoder_norm=True`` in Ming's mlp/config.json refers to
# applying ``F.normalize(..., dim=-1)`` (L2 normalization) on the
# FINAL cap_feats AFTER proj_out — NOT an intermediate RMSNorm. See
# modeling_bailingmm2.py::get_condition_embeds_for_image_gen. We keep
# ``self.norm = nn.Identity`` and apply the L2 normalize explicitly
# at the end of ``forward``.
self.norm = nn.Identity()
# proj_out: align connector_hidden_size -> diffusion_c_input_dim.
c_out = self.config.diffusion_c_input_dim
logger.info(
"[MingConditionEncoder] adding proj_out: %d -> %d (bias=True)",
self.connector_hidden_size,
c_out,
)
self.proj_out = nn.Linear(self.connector_hidden_size, c_out, bias=True)
mlp_path = model_path / self.config.mlp_subfolder
mlp_cfg_path = mlp_path / "config.json"
if mlp_cfg_path.exists() and not json.loads(mlp_cfg_path.read_text()).get("use_identity_mlp", False):
# MingImagePipeline skips ZImageModel_withMLP, only correct when its inner MLP is Identity.
raise NotImplementedError(f"{mlp_cfg_path} has use_identity_mlp=False; ToClipMLP path not implemented.")
self._load_optional_mlp_weights(mlp_path)
if self._target_device is not None:
self.to(self._target_device)
if self._target_dtype is not None:
self.to(dtype=self._target_dtype)
logger.info(
"[MingConditionEncoder] ready: in=%d -> conn=%d -> out=%d",
self.thinker_hidden_size,
self.connector_hidden_size,
c_out,
)
def _load_optional_mlp_weights(self, mlp_path: Path) -> None:
"""Load proj_in / proj_out (and optional norm) weights from mlp/.
Expected keys — observed on inclusionAI/Ming-flash-omni-2.0:
proj_in.weight [1536, 4096]
proj_in.bias [1536]
proj_out.weight [2560, 1536]
proj_out.bias [2560]
query_tokens_dict.16x16 [256, 4096] -> thinker-side, skipped here
(optional) norm.weight [1536]
Any extra keys are logged as warnings so we don't silently miss new
fields. Missing proj weights are fatal: they are required for the
condition path to be meaningful.
"""
if not mlp_path.exists():
logger.warning(
"[MingConditionEncoder] mlp/ subfolder missing at %s — proj/norm "
"will stay randomly initialized. EXPECT BAD IMAGES until this "
"is fixed on real hardware.",
mlp_path,
)
return
try:
from safetensors.torch import load_file # type: ignore
except ImportError:
logger.exception("[MingConditionEncoder] safetensors not installed")
return
candidates = sorted(mlp_path.glob("*.safetensors"))
if not candidates:
candidates = sorted(mlp_path.glob("*.bin"))
if not candidates:
logger.warning("[MingConditionEncoder] no weight files under %s", mlp_path)
return
state: dict[str, torch.Tensor] = {}
for p in candidates:
logger.info("[MingConditionEncoder] reading mlp weights: %s", p)
if p.suffix == ".safetensors":
state.update(load_file(str(p)))
else:
state.update(torch.load(str(p), map_location="cpu"))
logger.info(
"[MingConditionEncoder] mlp/ keys: %s",
sorted(state.keys()),
)
handled: set[str] = set()
def _copy(dst: nn.Parameter | torch.Tensor, src_key: str) -> bool:
src = state.get(src_key)
if src is None:
logger.error("[MingConditionEncoder] mlp/ missing key %r", src_key)
return False
if tuple(src.shape) != tuple(dst.shape):
logger.error(
"[MingConditionEncoder] mlp/%s shape mismatch: checkpoint=%s, module=%s",
src_key,
tuple(src.shape),
tuple(dst.shape),
)
return False
with torch.no_grad():
dst.copy_(src.to(dtype=dst.dtype, device=dst.device))
handled.add(src_key)
logger.info(
"[MingConditionEncoder] loaded mlp/%s -> %s",
src_key,
tuple(dst.shape),
)
return True
ok_w = _copy(self.proj_in.weight, "proj_in.weight")
ok_b = _copy(self.proj_in.bias, "proj_in.bias")
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):
logger.error(
"[MingConditionEncoder] proj_in/proj_out NOT fully loaded; diffusion conditioning will be garbage."
)
# Optional norm weight (Ming uses plain RMSNorm; may or may not ship).
if "norm.weight" in state and hasattr(self.norm, "weight"):
_copy(self.norm.weight, "norm.weight")
# query_tokens_dict lives in mlp/ but is consumed on the thinker side
# — we neither need nor load it here. Just log the shape so the
# thinker-side patch knows what to expect.
for k, v in state.items():
if k.startswith("query_tokens_dict"):
logger.info(
"[MingConditionEncoder] thinker-side parameter %s shape=%s (NOT loaded here; thinker must own it)",
k,
tuple(v.shape),
)
handled.add(k)
leftover = set(state.keys()) - handled
if leftover:
logger.warning("[MingConditionEncoder] mlp/ unhandled keys: %s", sorted(leftover))
# ------------------------------------------------------------------
# Forward
# ------------------------------------------------------------------
def forward(
self,
thinker_hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None = None,
) -> torch.Tensor:
"""Encode thinker hidden states into DiT condition embeddings.
Args:
thinker_hidden_states: ``[B, N, thinker_hidden_size]`` — sliced at
the learnable query-token positions by the stage input
processor before being passed here.
attention_mask: Optional ``[B, N]`` mask. Defaults to all-ones.
Returns:
``[B, N, diffusion_c_input_dim]`` condition tensor ready for the
ZImage transformer's ``cap_feats`` input.
"""
if self.connector is None:
raise RuntimeError("MingConditionEncoder.load_from_checkpoint() must be called before forward().")
if thinker_hidden_states.dim() != 3:
raise ValueError(f"expected [B, N, H], got shape {tuple(thinker_hidden_states.shape)}")
b, n, _ = thinker_hidden_states.shape
logger.debug(
"[MingCondEnc] input shape=%s dtype=%s", tuple(thinker_hidden_states.shape), thinker_hidden_states.dtype
)
x = self.proj_in(thinker_hidden_states) # [B, N, conn_hidden]
# Ming's ``get_condition_embeds_for_image_gen`` passes a 4D full-ones
# attention mask of shape [B, 1, N, N] to the Qwen2 connector,
# forcing full bidirectional self-attention over all query positions.
if attention_mask is None:
attention_mask = torch.ones(
(b, 1, n, n),
dtype=x.dtype,
device=x.device,
)
elif attention_mask.dim() == 2:
mask_2d = attention_mask.to(x.dtype)
attention_mask = mask_2d[:, None, None, :].expand(b, 1, n, n)
out = self.connector(
inputs_embeds=x,
attention_mask=attention_mask,
use_cache=False,
output_hidden_states=True,
return_dict=True,
)
hidden = out.hidden_states[-1] # [B, N, conn_hidden]
cap_feats = self.proj_out(hidden) # [B, N, diffusion_c_input_dim]
# 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.config.text_encoder_norm:
cap_feats = cap_feats * 1000.0
logger.debug("[MingCondEnc] output shape=%s dtype=%s", tuple(cap_feats.shape), cap_feats.dtype)
return cap_feats
# ------------------------------------------------------------------
# Utility
# ------------------------------------------------------------------
@torch.no_grad()
def zero_negative(
self,
cap_feats: torch.Tensor,
) -> torch.Tensor:
"""Return a zero tensor shaped like ``cap_feats`` for CFG negatives."""
return torch.zeros_like(cap_feats)
def extra_repr(self) -> str:
return (
f"thinker_hidden_size={self.thinker_hidden_size}, "
f"connector_hidden_size={self.connector_hidden_size}, "
f"diffusion_c_input_dim={self.config.diffusion_c_input_dim}, "
f"text_encoder_norm={self.config.text_encoder_norm}"
)
__all__ = ["MingConditionEncoder"]
@@ -0,0 +1,50 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 The vLLM-Omni team.
"""Ming-specific subclass of ZImageTransformer2DModel that supports ``ref_x``.
Ming's img2img path concatenates a VAE-encoded reference latent along the
frame axis before patchification, then drops the reference portion from the
unpatchified output. This is a surgical override — everything else (attention,
RoPE, final layer) stays on the parent implementation.
"""
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 MingZImageTransformer2DModel(ZImageTransformer2DModel):
"""ZImage DiT with Ming's reference-latent support."""
def forward(
self,
x: list[torch.Tensor],
t,
cap_feats: list[torch.Tensor],
patch_size=2,
f_patch_size=1,
):
ref_latent = get_forward_context().ref_latent if is_forward_context_available() else None
if ref_latent is not None:
per_item = ref_latent[0].unsqueeze(1).to(dtype=x[0].dtype, device=x[0].device) # [C, 1, H, W]
x = [torch.cat([img, per_item], dim=1) for img in x]
return super().forward(x, t, cap_feats, patch_size=patch_size, f_patch_size=f_patch_size)
def unpatchify(
self,
x: list[torch.Tensor],
size: list[tuple],
patch_size,
f_patch_size,
) -> list[torch.Tensor]:
out = super().unpatchify(x, size, patch_size, f_patch_size)
# No-op when F==1 (pure t2i); drops the reference-frame prediction when F==2.
return [t[:, :1, :, :] for t in out]
__all__ = ["MingZImageTransformer2DModel"]
@@ -0,0 +1,520 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 The vLLM-Omni team.
"""Ming-flash-omni-2.0 imagegen (text-to-image / img2img) diffusion pipeline.
Cross-stage data flow:
Stage 0 (thinker, llm) Stage 1 (imagegen, diffusion)
──────────────────── ──────────────────────────────
forward returns thinker2imagegen hook slices
multimodal_output[ final_hidden_states at
"final_hidden_states"] <imagePatch> positions,
↓ returns list[dict] with
shared_memory_connector {"extra": {"thinker_hidden_states"}}
↓ ──── via OmniMsgpackEncoder ────>
MingImagePipeline.forward(req):
hidden = req.prompts[0]["extra"][...]
cond = condition_encoder(hidden)
img = ZImagePipeline-style loop
return DiffusionOutput(output=img)
"""
from __future__ import annotations
import logging
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import torch
import torch.nn as nn
from diffusers.image_processor import VaeImageProcessor
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl import DistributedAutoencoderKL
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import set_forward_context_ref_latent
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
from vllm_omni.diffusion.model_loader.hub_prefetch import prefetch_subfolders
from vllm_omni.diffusion.models.ming_flash_omni.byte5_encoder import (
MingByT5Encoder,
)
from vllm_omni.diffusion.models.ming_flash_omni.condition_encoder import (
MingConditionEncoder,
)
from vllm_omni.diffusion.models.ming_flash_omni.ming_zimage_transformer import (
MingZImageTransformer2DModel,
)
from vllm_omni.diffusion.models.z_image.pipeline_z_image import ZImagePipeline
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.model_executor.model_loader.weight_utils import (
download_weights_from_hf_specific,
)
from vllm_omni.transformers_utils.configs.ming_flash_omni import MingImageGenConfig
logger = logging.getLogger(__name__)
@dataclass
class _ZPipelineSamplingParams:
"""Typed shim satisfying the attributes ZImagePipeline.forward reads
from ``req.sampling_params``. Unlike SimpleNamespace this fails loudly
at construction if a required field is missing."""
height: int
width: int
num_inference_steps: int
guidance_scale: float
generator: torch.Generator | None = None
strength: float | None = None
sigmas: list[float] | None = None
max_sequence_length: int = 512
guidance_rescale: float | None = None
num_outputs_per_prompt: int = 1
@dataclass
class _ZPipelineRequest:
"""Typed shim satisfying the attributes ZImagePipeline.forward reads
from ``req``."""
request_id: str
sampling_params: _ZPipelineSamplingParams
prompts: list[dict[str, Any]] = field(default_factory=lambda: [{"prompt": "", "negative_prompt": ""}])
class MingImagePipeline(ZImagePipeline):
"""Ming-flash-omni-2.0 text-to-image diffusion pipeline.
Ming-specific components added on top of the inherited contract:
* ``condition_encoder`` — Qwen2 connector + proj_in/out + F.normalize×1000
* ``byte5`` — Optional ByT5 glyph encoder (loaded if checkpoint
ships ``byt5/``)
"""
def __init__(
self,
*,
od_config: OmniDiffusionConfig,
prefix: str = "", # noqa: ARG002
) -> None:
# Skip ZImagePipeline.__init__ (it would eagerly load the Z-Image text
# encoder/tokenizer that Ming replaces with its own condition_encoder).
nn.Module.__init__(self)
model_path = od_config.model
if not os.path.exists(model_path):
model_path = download_weights_from_hf_specific(model_path, od_config.revision, ["*"])
dtype = getattr(od_config, "dtype", torch.bfloat16)
local_files_only = os.path.exists(model_path)
self.od_config = od_config
self._execution_device = get_local_device()
self.device = self._execution_device # Ming convention alias
self._dtype = dtype
# Ming's per-checkpoint image-gen configuration. We cannot rely on
# ``od_config.hf_config.image_gen_config`` because the diffusion
# stage is started with ``hf_config_name: thinker_config`` (the
# BailingMM2Config), which does not carry a MingImageGenConfig.
# Fall back to defaults that match the released checkpoint.
self.image_gen_config = MingImageGenConfig()
logger.info(
"[MingImagePipeline] init: model=%s dtype=%s image_gen_config=%s",
model_path,
dtype,
self.image_gen_config,
)
# ----- weights_sources: DiT transformer + VAE.
self.weights_sources = [
DiffusersPipelineLoader.ComponentSource(
model_or_path=model_path,
subfolder=self.image_gen_config.transformer_subfolder,
revision=od_config.revision,
prefix="transformer.",
fall_back_to_pt=True,
),
DiffusersPipelineLoader.ComponentSource(
model_or_path=model_path,
subfolder=self.image_gen_config.vae_subfolder,
revision=od_config.revision,
prefix="vae.",
),
]
prefetch_subfolders(
model_path,
[self.image_gen_config.scheduler_subfolder, self.image_gen_config.vae_subfolder],
local_files_only=local_files_only,
)
# ----- Scheduler: load config-only from disk + Ming-specific override.
self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
model_path,
subfolder=self.image_gen_config.scheduler_subfolder,
local_files_only=local_files_only,
)
# Ming forces use_dynamic_shifting=True at runtime regardless of what
# the checkpoint scheduler_config.json ships.
self.scheduler.config["use_dynamic_shifting"] = True
logger.info(
"[MingImagePipeline] scheduler: %s (use_dynamic_shifting=True)",
type(self.scheduler).__name__,
)
# ----- VAE: DistributedAutoencoderKL.
vae_config = DistributedAutoencoderKL.load_config(
model_path, subfolder=self.image_gen_config.vae_subfolder, local_files_only=local_files_only
)
self.vae = DistributedAutoencoderKL.from_config(vae_config).to(self._execution_device, dtype=dtype)
self.vae.eval()
# ----- DiT transformer.
self.transformer = MingZImageTransformer2DModel(quant_config=None)
# Ming brings its own conditioning path — no Z-Image text_encoder /
# tokenizer.
self.text_encoder = None
self.tokenizer = None
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2, do_convert_rgb=True)
self.setup_diffusion_pipeline_profiler(
enable_diffusion_pipeline_profiler=getattr(od_config, "enable_diffusion_pipeline_profiler", False)
)
# ----- Condition encoder (Qwen2 connector + proj_in/out + norm×1000).
self.condition_encoder = MingConditionEncoder(
self.image_gen_config,
thinker_hidden_size=self.image_gen_config.thinker_hidden_size,
device=self.device,
dtype=dtype,
)
self.condition_encoder.load_from_checkpoint(model_path)
# Optional ByT5 glyph/text encoder. Only loaded when the checkpoint
# ``extra_args.image_gen.byte5_text`` requests will be ignored.
byte5_dir = Path(model_path) / "byt5"
if byte5_dir.exists():
self.byte5 = MingByT5Encoder.from_checkpoint(byte5_dir, device=self.device, dtype=dtype)
else:
self.byte5 = None
logger.info("[MingImagePipeline] no byt5/ subfolder at %s; ByT5 enhancement disabled", byte5_dir)
logger.info("[MingImagePipeline] ready — vae_scale_factor=%d", self.vae_scale_factor)
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
@staticmethod
def _resolve_byte5_texts(extra: dict, sampling_params) -> list[str]:
"""Resolve byte5 glyph texts.
Two sources, in order of priority:
1. ``extra["byte5_text"]`` — auto-extracted from the user prompt's
quoted spans by ``thinker2imagegen`` (already wrapped as
``'Text "<glyph>". '`` by Ming's ``get_text_from_prompt``).
2. ``sampling_params.extra_args["image_gen"]["byte5_text"]`` — an
explicit override for programmatic callers; raw strings without
the ``Text "..."`` wrapper are auto-wrapped here to match the
distribution ByT5 was trained on.
"""
# Source 1: auto-extracted, already wrapped. Return as-is if non-empty.
raw = extra.get("byte5_text")
if isinstance(raw, str):
raw = [raw]
if isinstance(raw, list):
cleaned = [t for t in raw if isinstance(t, str) and t.strip()]
if cleaned:
return cleaned
# Source 2: explicit override — wrap raw strings so the byte5 encoder
# sees the same ``Text "<glyph>". `` format Ming used during training.
raw = ((getattr(sampling_params, "extra_args", None) or {}).get("image_gen") or {}).get("byte5_text")
if isinstance(raw, str):
raw = [raw]
if isinstance(raw, list):
out: list[str] = []
for t in raw:
if not isinstance(t, str):
continue
s = t.strip()
if not s:
continue
# Don't double-wrap if the caller already supplied ``Text "...". ``.
out.append(s if s.startswith('Text "') else f'Text "{s}". ')
if out:
return out
return []
@torch.inference_mode()
def _encode_reference_image(self, ref, height: int, width: int) -> torch.Tensor | None:
"""Turn a PIL/tensor reference image into a VAE latent for ``ref_x``.
Applies the same shift/scale Ming uses (``(z - shift_factor) * scaling_factor``)
so the concatenated frame lives in the DiT's latent space.
"""
if ref is None:
return None
if not isinstance(ref, torch.Tensor):
ref = self.image_processor.preprocess(ref, height, width)
ref = ref.to(device=self.device, dtype=self.vae.dtype)
latent = self.vae.encode(ref).latent_dist.mode()
return (latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
# ------------------------------------------------------------------
# Forward
# ------------------------------------------------------------------
@torch.inference_mode()
def forward(self, req: OmniDiffusionRequest) -> DiffusionOutput:
"""Run one text-to-image generation request.
Args:
req: Diffusion request. The cross-stage thinker hidden states
must be present at
``req.prompts[0]["extra"]["thinker_hidden_states"]`` as a
``[N, H]`` (or ``[1, N, H]``) tensor, placed there by
``thinker2imagegen``.
Returns:
DiffusionOutput with ``.output`` set to a ``[B, 3, H, W]``
image tensor in ``[-1, 1]``. The vllm-omni diffusion engine's
output adapter converts this to PIL/base64 downstream.
"""
first_prompt = req.prompts[0] if req.prompts else None
if isinstance(first_prompt, str):
prompt_dict: dict[str, Any] = {}
elif isinstance(first_prompt, dict):
prompt_dict = first_prompt
elif first_prompt is not None and hasattr(first_prompt, "_asdict"):
prompt_dict = first_prompt._asdict()
elif first_prompt is not None and hasattr(first_prompt, "__dict__"):
prompt_dict = vars(first_prompt)
else:
prompt_dict = {}
extra = prompt_dict.get("extra") or {}
hidden = extra.get("thinker_hidden_states")
if hidden is None:
# Same dual-path convention as glm_image: also check
# ``sampling_params.extra_args``.
hidden = (req.sampling_params.extra_args or {}).get("thinker_hidden_states")
if hidden is None:
scale = self.image_gen_config.img_gen_scales[-1]
num_query_tokens = scale * scale
hidden = torch.zeros(
(num_query_tokens, self.image_gen_config.thinker_hidden_size),
dtype=self._dtype,
device=self.device,
)
logger.warning(
"[MingImagePipeline.forward] 'thinker_hidden_states' missing "
"from request; falling back to zero-conditioning %s. This is "
"expected during warmup; for real requests verify that "
"`custom_process_input_func: thinker2imagegen` is set on the "
"diffusion stage in the YAML.",
tuple(hidden.shape),
)
if not isinstance(hidden, torch.Tensor):
raise TypeError(
f"[MingImagePipeline] 'thinker_hidden_states' must be a Tensor, got {type(hidden).__name__}"
)
# Move to the pipeline's device+dtype.
target_device = next(self.parameters()).device
target_dtype = next(self.parameters()).dtype
hidden = hidden.to(device=target_device, dtype=target_dtype)
if hidden.dim() == 2:
hidden = hidden.unsqueeze(0) # [N, H] -> [1, N, H]
logger.debug(
"[MingImagePipeline.forward] thinker_hidden_states=%s on %s (%s)",
tuple(hidden.shape),
target_device,
target_dtype,
)
# ----- Condition encoder → cap_feats
cap_feats = self.condition_encoder(hidden)
logger.debug("[MingImagePipeline.forward] cap_feats=%s", tuple(cap_feats.shape))
# Real negative CFG conditioning (opt-in). See expand_cfg_prompts.
negative_hidden = extra.get("negative_thinker_hidden_states")
negative_cap_feats = None
if isinstance(negative_hidden, torch.Tensor):
negative_hidden = negative_hidden.to(device=target_device, dtype=target_dtype)
if negative_hidden.dim() == 2:
negative_hidden = negative_hidden.unsqueeze(0)
negative_cap_feats = self.condition_encoder(negative_hidden)
logger.debug("[MingImagePipeline.forward] negative_cap_feats=%s", tuple(negative_cap_feats.shape))
# ByT5 text enhancement (opt-in). Appends glyph-aware features along
# the sequence dim; negative side gets zeros for the byte5 portion so
# CFG doesn't push away from the rendered text.
byte5_texts = self._resolve_byte5_texts(extra, req.sampling_params)
if byte5_texts and self.byte5 is not None:
byte5_feats = self.byte5(byte5_texts).to(device=target_device, dtype=target_dtype)
cap_feats = torch.cat((cap_feats, byte5_feats), dim=1)
if negative_cap_feats is not None:
negative_cap_feats = torch.cat((negative_cap_feats, torch.zeros_like(byte5_feats)), dim=1)
logger.debug("[MingImagePipeline.forward] byte5 cat'd: cap_feats=%s", tuple(cap_feats.shape))
# Sampling knobs: extra_args.image_gen.* > sampling_params.* > MingImageGenConfig defaults.
sp = req.sampling_params
cfg = self.image_gen_config
ig = (sp.extra_args or {}).get("image_gen") or {}
resolved: dict[str, Any] = {}
for ig_key, sp_attr, default in (
("height", "height", cfg.default_height),
("width", "width", cfg.default_width),
("steps", "num_inference_steps", cfg.num_inference_steps),
("cfg", "guidance_scale", cfg.guidance_scale),
("seed", "seed", None),
):
for v in (ig.get(ig_key), getattr(sp, sp_attr), default):
if v is not None:
resolved[ig_key] = v
break
height = int(resolved["height"])
width = int(resolved["width"])
num_inference_steps = int(resolved["steps"])
guidance_scale = float(resolved["cfg"])
seed = resolved.get("seed")
# Always rebuild the generator from the resolved seed. Reusing
# ``sp.generator`` causes two problems:
# (1) if the caller pre-seeded it with sp.seed (e.g. the top-level
# ``seed`` key on OmniDiffusionSamplingParams), any override via
# ``extra_args.image_gen.seed`` would be silently ignored; and
# (2) a persistent generator instance accumulates state across
# requests → same-seed replays produce different outputs.
if seed is not None:
generator = torch.Generator(device=target_device).manual_seed(int(seed))
else:
generator = sp.generator
# Format prompt_embeds / negative_prompt_embeds as list[Tensor]
# (one entry per request) — matches ZImagePipeline's contract when
# prompt_embeds are pre-computed.
prompt_embeds = [cap_feats[i] for i in range(cap_feats.shape[0])]
if negative_cap_feats is not None:
negative_prompt_embeds = [negative_cap_feats[i] for i in range(negative_cap_feats.shape[0])]
else:
negative_prompt_embeds = [self.condition_encoder.zero_negative(e) for e in prompt_embeds]
z_sp = _ZPipelineSamplingParams(
height=height,
width=width,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
generator=generator,
)
z_req = _ZPipelineRequest(
request_id=req.request_id or "ming-imagegen",
sampling_params=z_sp,
)
# Reference image (img2img) → VAE-encoded latent published on the
# active ForwardContext so MingZImageTransformer2DModel can read it
# from request scope inside its forward().
ref_latent = self._encode_reference_image(extra.get("reference_image"), height, width)
set_forward_context_ref_latent(ref_latent)
logger.debug(
"[MingImagePipeline.forward] running z_pipeline hw=(%d,%d) steps=%d cfg=%.2f seed=%s overrides=%s ref=%s",
height,
width,
num_inference_steps,
guidance_scale,
seed,
ig,
None if ref_latent is None else tuple(ref_latent.shape),
)
try:
output = super().forward(
z_req,
prompt=None,
height=height,
width=width,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
generator=generator,
output_type="pt",
return_dict=True,
)
finally:
set_forward_context_ref_latent(None)
if hasattr(output, "output") and output.output is not None:
raw = output.output
elif hasattr(output, "images"):
raw = output.images
else:
raw = output
if not isinstance(raw, torch.Tensor):
raise RuntimeError(f"ZImagePipeline returned non-tensor output: {type(raw).__name__}")
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
"[MingImagePipeline.forward] produced image tensor shape=%s range=[%.3f,%.3f]",
tuple(raw.shape),
raw.float().min().item(),
raw.float().max().item(),
)
return DiffusionOutput(output=raw)
# ----------------------------------------------------------------------
# Helpers
# ----------------------------------------------------------------------
def get_ming_image_post_process_func(od_config: OmniDiffusionConfig):
"""Return a post-process callable that converts the raw VAE tensor to PIL.
The diffusion engine calls ``post_process_func(output_data)`` where
``output_data`` is the ``DiffusionOutput.output`` tensor returned by
``MingImagePipeline.forward``. It has shape ``[B, 3, H, W]`` in ``[-1, 1]``
(Z-image VAE convention). We run the standard ``VaeImageProcessor``
postprocess to convert it to ``list[PIL.Image]`` which vllm-omni's
``OmniRequestOutput.from_diffusion`` then bubbles up as
``omni_outputs.images`` for serving_chat to base64-encode.
Registered via ``_DIFFUSION_POST_PROCESS_FUNCS["MingImagePipeline"]``
in vllm_omni/diffusion/registry.py.
"""
import json
model_path = od_config.model
vae_config_path = os.path.join(model_path, "vae", "config.json")
try:
with open(vae_config_path) as f:
vae_cfg = json.load(f)
block_out_channels = vae_cfg.get("block_out_channels", [128, 256, 512, 512])
vae_scale_factor = 2 ** (len(block_out_channels) - 1)
except Exception:
vae_scale_factor = 8 # Ming's Flux-format VAE default
image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor * 2, do_convert_rgb=True)
def post_process_func(images: torch.Tensor):
# VaeImageProcessor.postprocess with default output_type="pil"
# returns ``list[PIL.Image]``.
return image_processor.postprocess(images.float())
return post_process_func
__all__ = [
"MingImagePipeline",
"get_ming_image_post_process_func",
]
@@ -0,0 +1,129 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 The vLLM-Omni team.
"""T5EncoderBlockByT5Mapper — Ming's per-block T5 stack mapping byte5 features
onto the DiT condition space.
"""
from __future__ import annotations
from collections.abc import Iterable
import torch
import torch.nn as nn
from diffusers.models.modeling_utils import ModelMixin
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.models.t5_encoder.t5_encoder import T5Block
class T5EncoderBlockByT5Mapper(ModelMixin):
"""Stacks ``num_layers`` T5 encoder blocks on top of byte5 features and
projects them to ``sdxl_channels`` (= Ming's ``diffusion_c_input_dim``).
"""
def __init__(self, byte5_config, num_layers: int, sdxl_channels: int | None = None) -> None:
super().__init__()
if num_layers > 0:
self.blocks = nn.ModuleList(
[
T5Block(
byte5_config,
has_relative_attention_bias=(i == 0),
prefix=f"blocks.{i}",
)
for i in range(num_layers)
]
)
else:
self.blocks = None
self.layer_norm = RMSNorm(byte5_config.d_model, eps=byte5_config.layer_norm_epsilon)
if sdxl_channels is not None:
self.channel_mapper = nn.Linear(byte5_config.d_model, sdxl_channels)
self.final_layer_norm = RMSNorm(sdxl_channels, eps=byte5_config.layer_norm_epsilon)
else:
self.channel_mapper = None
self.final_layer_norm = None
def get_extended_attention_mask(self, attention_mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
if attention_mask.dim() == 3:
extended = attention_mask[:, None, :, :]
elif attention_mask.dim() == 2:
extended = attention_mask[:, None, None, :]
else:
raise ValueError(f"Unexpected attention_mask shape {tuple(attention_mask.shape)}")
extended = extended.to(dtype=dtype)
return (1.0 - extended) * torch.finfo(dtype).min
def forward(self, inputs_embeds: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
extended_mask = self.get_extended_attention_mask(attention_mask, dtype=self.dtype)
hidden_states = inputs_embeds
position_bias = None
if self.blocks is not None:
for block in self.blocks:
hidden_states, position_bias = block(
hidden_states,
mask=extended_mask,
position_bias=position_bias,
)
hidden_states = self.layer_norm(hidden_states)
if self.channel_mapper is not None:
hidden_states = self.channel_mapper(hidden_states)
hidden_states = self.final_layer_norm(hidden_states)
return hidden_states
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load Ming's HF-format byte5_mapper checkpoint into the fused
TP-aware layers.
Source format (from ``byte5_mapper.pt``):
blocks.{i}.layer.0.SelfAttention.{q,k,v,o}.weight
blocks.{i}.layer.1.DenseReluDense.{wi_0,wi_1,wo}.weight
blocks.{i}.layer.{0,1}.layer_norm.weight
{layer_norm, channel_mapper, final_layer_norm}.{weight,bias}
Target format (after ``T5Block`` from t5_encoder.py):
blocks.{i}.layer.0.SelfAttention.qkv_proj.weight (fused q+k+v)
blocks.{i}.layer.1.DenseReluDense.wi.weight (fused wi_0+wi_1)
(others identical)
"""
stacked_params_mapping = [
(".qkv_proj.", ".q.", "q"),
(".qkv_proj.", ".k.", "k"),
(".qkv_proj.", ".v.", "v"),
(".DenseReluDense.wi.", ".DenseReluDense.wi_0.", 0),
(".DenseReluDense.wi.", ".DenseReluDense.wi_1.", 1),
]
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
for name, loaded_weight in weights:
matched = False
for target_substr, source_substr, shard_id in stacked_params_mapping:
if source_substr not in name:
continue
target_name = name.replace(source_substr, target_substr, 1)
if target_name in params_dict:
param = params_dict[target_name]
param.weight_loader(param, loaded_weight, shard_id)
loaded_params.add(target_name)
matched = True
break
if matched:
continue
if name in params_dict:
param = params_dict[name]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)
loaded_params.add(name)
return loaded_params
__all__ = ["T5EncoderBlockByT5Mapper"]
@@ -147,6 +147,8 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
ref_text = None
lang = "None"
instruct = "None"
extra = req.sampling_params.extra_args or {}
seed = extra.get("seed", None)
voice_name = None
if isinstance(prompt, dict):
@@ -157,7 +159,6 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
voice_name = prompt.get("voice_name")
lang = prompt.get("lang")
instruct = prompt.get("instruct")
# OmniTextPrompt format (used by offline Omni.generate path):
# ref_audio comes via multi_modal_data["audio"] and the rest via
# mm_processor_kwargs. Fall back to those when top-level keys are
@@ -262,7 +263,6 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
else:
cond_ids = torch.cat([text_ids, target_ids], dim=1)
cond_len = cond_ids.shape[1]
uncond_ids = target_ids.clone()
uncond_len = target_len
max_len = max(cond_len, uncond_len)
@@ -297,8 +297,8 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
layer_penalty_factor=self.layer_penalty_factor,
position_temperature=self.position_temperature,
class_temperature=self.class_temperature,
seed=seed,
)
# Decode tokens to audio
audio = self.decoder(tokens) # [1, 1, samples]
@@ -168,7 +168,10 @@ class OvisImagePipeline(nn.Module, CFGParallelMixin, DiffusionPipelineProfilerMi
)
self.text_encoder = Qwen3Model.from_pretrained(
model, subfolder="text_encoder", local_files_only=local_files_only
model,
subfolder="text_encoder",
local_files_only=local_files_only,
torch_dtype=od_config.dtype,
)
self.vae = AutoencoderKL.from_pretrained(model, subfolder="vae", local_files_only=local_files_only).to(
@@ -17,7 +17,6 @@ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
from diffusers.models.modeling_outputs import Transformer2DModelOutput
from diffusers.models.normalization import AdaLayerNormContinuous
from vllm.logger import init_logger
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
QKVParallelLinear,
@@ -44,11 +43,16 @@ from vllm_omni.diffusion.distributed.sp_plan import (
)
from vllm_omni.diffusion.forward_context import get_forward_context
from vllm_omni.diffusion.layers.adalayernorm import AdaLayerNorm
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
logger = init_logger(__name__)
def _join_prefix(prefix: str, suffix: str) -> str:
return f"{prefix}.{suffix}" if prefix else suffix
class ImageRopePrepare(nn.Module):
"""Prepares image hidden_states and RoPE embeddings for sequence parallel.
@@ -471,7 +475,12 @@ class FeedForward(nn.Module):
layers: list[nn.Module] = [
ColumnParallelApproxGELU(
dim, inner_dim, approximate="tanh", bias=bias, quant_config=quant_config, prefix=prefix
dim,
inner_dim,
approximate="tanh",
bias=bias,
quant_config=quant_config,
prefix=_join_prefix(prefix, "net.0.proj"),
),
nn.Identity(), # placeholder for weight loading
RowParallelLinear(
@@ -480,7 +489,7 @@ class FeedForward(nn.Module):
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=prefix,
prefix=_join_prefix(prefix, "net.2"),
),
]
@@ -507,6 +516,7 @@ class QwenImageCrossAttention(nn.Module):
context_pre_only: bool = False,
out_dim: int | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> None:
super().__init__()
assert dim % num_heads == 0
@@ -523,7 +533,7 @@ class QwenImageCrossAttention(nn.Module):
head_size=self.head_dim,
total_num_heads=num_heads,
quant_config=quant_config,
prefix="to_qkv",
prefix=_join_prefix(prefix, "to_qkv"),
)
self.query_num_heads = self.to_qkv.num_heads
self.kv_num_heads = self.to_qkv.num_kv_heads
@@ -539,7 +549,7 @@ class QwenImageCrossAttention(nn.Module):
head_size=head_dim,
total_num_heads=num_heads,
quant_config=quant_config,
prefix="add_kv_proj",
prefix=_join_prefix(prefix, "add_kv_proj"),
)
self.add_query_num_heads = self.add_kv_proj.num_heads
self.add_kv_num_heads = self.add_kv_proj.num_kv_heads
@@ -552,7 +562,7 @@ class QwenImageCrossAttention(nn.Module):
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix="to_add_out",
prefix=_join_prefix(prefix, "to_add_out"),
)
assert not pre_only
@@ -563,7 +573,7 @@ class QwenImageCrossAttention(nn.Module):
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix="to_out",
prefix=_join_prefix(prefix, "to_out"),
)
self.norm_added_q = RMSNorm(head_dim, eps=eps)
@@ -697,6 +707,7 @@ class QwenImageTransformerBlock(nn.Module):
eps: float = 1e-6,
zero_cond_t: bool = False,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
super().__init__()
@@ -705,18 +716,20 @@ class QwenImageTransformerBlock(nn.Module):
self.attention_head_dim = attention_head_dim
# Image processing modules.
# Modulation linear is kept full precision (quant_config=None) — it
# Modulation linear is kept unquantized (quant_config=None) — it
# produces shift/scale/gate values that are precision-sensitive
# (see #2728).
# (see #2728). Use column TP with gather_output=True so weights are
# sharded while downstream modulation still receives full [B, 6 * dim].
self.img_mod = nn.Sequential(
nn.SiLU(),
ReplicatedLinear(
ColumnParallelLinear(
dim,
6 * dim,
bias=True,
gather_output=True,
return_bias=False,
quant_config=None,
prefix="img_mod.1",
prefix=_join_prefix(prefix, "img_mod.1"),
),
)
self.img_norm1 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
@@ -727,26 +740,38 @@ class QwenImageTransformerBlock(nn.Module):
context_pre_only=False,
head_dim=attention_head_dim,
quant_config=quant_config,
prefix=_join_prefix(prefix, "attn"),
)
self.img_norm2 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
self.img_mlp = FeedForward(dim=dim, dim_out=dim, quant_config=quant_config, prefix="img_mlp")
self.img_mlp = FeedForward(
dim=dim,
dim_out=dim,
quant_config=quant_config,
prefix=_join_prefix(prefix, "img_mlp"),
)
# Text processing modules.
self.txt_mod = nn.Sequential(
nn.SiLU(),
ReplicatedLinear(
ColumnParallelLinear(
dim,
6 * dim,
bias=True,
gather_output=True,
return_bias=False,
quant_config=None,
prefix="txt_mod.1",
prefix=_join_prefix(prefix, "txt_mod.1"),
),
)
self.txt_norm1 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
# Text doesn't need separate attention - it's handled by img_attn joint computation
self.txt_norm2 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
self.txt_mlp = FeedForward(dim=dim, dim_out=dim, quant_config=quant_config, prefix="txt_mlp")
self.txt_mlp = FeedForward(
dim=dim,
dim_out=dim,
quant_config=quant_config,
prefix=_join_prefix(prefix, "txt_mlp"),
)
self.zero_cond_t = zero_cond_t
@@ -996,8 +1021,9 @@ class QwenImageTransformer2DModel(CachedTransformer):
attention_head_dim=attention_head_dim,
zero_cond_t=zero_cond_t,
quant_config=quant_config,
prefix=f"transformer_blocks.{i}",
)
for _ in range(num_layers)
for i in range(num_layers)
]
)
@@ -707,7 +707,17 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
return out.past_key_values, out.hidden_states
def _t2i_predict_v(
self, input_embeds, indexes_image, attn_mask, past_key_values, t, z, image_token_num, image_size=None, **_kw
self,
input_embeds,
indexes_image,
attn_mask,
past_key_values,
t,
z,
image_token_num,
image_size=None,
cache_dit_skip=False,
**_kw,
):
B, L = z.shape[0], z.shape[1]
outputs = self.language_model(
@@ -719,6 +729,7 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
attention_mask=attn_mask,
past_key_values=past_key_values,
update_cache=False,
cache_dit_skip=cache_dit_skip,
use_cache=True,
compute_logits=False,
)
@@ -1066,6 +1077,13 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
kv_cond = caches["cond"]
idx_cond = caches["idx_cond"]
mask_cond = caches["mask_cond"]
is_it2i = "img_cond" in caches
if is_it2i:
use_cfg = (t > p.cfg_interval[0] and t < p.cfg_interval[1]) or p.cfg_interval[0] == 0
needs_cfg = not (p.cfg_scale == 1 and p.img_cfg_scale == 1)
has_cached_partner = use_cfg and needs_cfg
else:
has_cached_partner = t >= p.cfg_interval[0] and t <= p.cfg_interval[1] and p.cfg_scale > 1
out_cond = self._t2i_predict_v(
image_embeds,
@@ -1076,9 +1094,9 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
z,
image_token_num=ns.token_h * ns.token_w,
image_size=p.image_size,
cache_dit_skip=not has_cached_partner,
)
is_it2i = "img_cond" in caches
if is_it2i:
return self._denoise_step_it2i(out_cond, image_embeds, ns, t, z, caches, p, step_i)
return self._denoise_step_t2i(out_cond, image_embeds, ns, t, z, caches, p, step_i)
@@ -1153,6 +1171,7 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
caches["img_cond"],
t,
z,
cache_dit_skip=True,
**predict_kw,
)
out_uncond = self._t2i_predict_v(
@@ -587,6 +587,12 @@ class SenseNovaU1DecoderLayer(nn.Module):
past_key_values=None,
**kwargs,
):
if isinstance(attention_mask, dict):
attention_mask = attention_mask.get(
self.attention_type,
attention_mask.get("full_attention"),
)
if exist_und and not exist_gen:
return self._forward_und(hidden_states, indexes, attention_mask, past_key_values, **kwargs)
if not exist_und and exist_gen:
@@ -663,7 +669,7 @@ class SenseNovaU1Model(nn.Module):
exist_und=exist_und,
exist_gen=exist_gen,
indexes=indexes,
attention_mask=causal_mask_mapping.get(layer.attention_type, causal_mask_mapping.get("full_attention")),
attention_mask=causal_mask_mapping,
past_key_values=past_key_values,
use_cache=use_cache,
**kwargs,
@@ -832,5 +832,8 @@ class ZImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
loaded_weights = loader.load_weights(weights)
# Record components loaded by diffusers submodules to satisfy strict checks.
loaded_weights |= {f"vae.{name}" for name, _ in self.vae.named_parameters()}
loaded_weights |= {f"text_encoder.{name}" for name, _ in self.text_encoder.named_parameters()}
# downstream pipelines (e.g. MingImagePipeline) may set ``self.text_encoder = None`` when they
# bring their own conditioning path.
if self.text_encoder is not None:
loaded_weights |= {f"text_encoder.{name}" for name, _ in self.text_encoder.named_parameters()}
return loaded_weights