Merge remote-tracking branch 'origin/main' into dev/vllm-align

This commit is contained in:
tzhouam committed 2026-02-11 01:44:54 +00:00
commit 279b6b5050
45 files changed
+2224 -349

No files matched your search

+5 -1
View File
@@ -45,6 +45,9 @@ class DiffusionParallelConfig:
cfg_parallel_size: int = 1
"""Number of Classifier Free Guidance (CFG) parallel groups."""
vae_patch_parallel_size: int = 1
"""Number of ranks used for VAE patch/tile parallelism (decode/encode)."""
@model_validator(mode="after")
def _validate_parallel_config(self) -> Self:
"""Validates the config relationships among the parallel strategies."""
@@ -56,6 +59,7 @@ class DiffusionParallelConfig:
assert self.ring_degree > 0, "Ring degree must be > 0"
assert self.cfg_parallel_size > 0, "CFG parallel size must be > 0"
assert self.cfg_parallel_size in [1, 2], f"CFG parallel size must be 1 or 2, but got {self.cfg_parallel_size}"
assert self.vae_patch_parallel_size > 0, "VAE patch parallel size must be > 0"
assert self.sequence_parallel_size == self.ulysses_degree * self.ring_degree, (
"Sequence parallel size must be equal to the product of ulysses degree and ring degree,"
f" but got {self.sequence_parallel_size} != {self.ulysses_degree} * {self.ring_degree}"
@@ -65,6 +69,7 @@ class DiffusionParallelConfig:
def __post_init__(self) -> None:
if self.sequence_parallel_size is None:
self.sequence_parallel_size = self.ulysses_degree * self.ring_degree
self.world_size = (
self.pipeline_parallel_size
* self.data_parallel_size
@@ -359,7 +364,6 @@ class OmniDiffusionConfig:
# support multi images input
supports_multimodal_inputs: bool = False
# Logging
log_level: str = "info"
# Omni configuration (injected from stage config)
@@ -57,7 +57,6 @@ _PP: PipelineGroupCoordinator | None = None
_CFG: GroupCoordinator | None = None
_DP: GroupCoordinator | None = None
_DIT: GroupCoordinator | None = None
_VAE: GroupCoordinator | None = None
def generate_masked_orthogonal_rank_groups(
@@ -344,7 +343,7 @@ def is_dp_last_group():
def get_dit_world_size():
"""Return world size for the DiT model (excluding VAE)."""
"""Return world size for the DiT model."""
return (
get_data_parallel_world_size()
* get_classifier_free_guidance_world_size()
@@ -354,22 +353,6 @@ def get_dit_world_size():
)
# Add VAE getter functions
def get_vae_parallel_group() -> GroupCoordinator:
assert _VAE is not None, "VAE parallel group is not initialized"
return _VAE
def get_vae_parallel_world_size():
"""Return world size for the VAE parallel group."""
return get_vae_parallel_group().world_size
def get_vae_parallel_rank():
"""Return my rank for the VAE parallel group."""
return get_vae_parallel_group().rank_in_group
# * SET
@@ -490,18 +473,6 @@ def get_dit_group():
return _DIT
def init_vae_group(
dit_parallel_size: int,
vae_parallel_size: int,
backend: str,
):
# Initialize VAE group first
global _VAE
assert _VAE is None, "VAE parallel group is already initialized"
vae_ranks = list(range(dit_parallel_size, dit_parallel_size + vae_parallel_size))
_VAE = torch.distributed.new_group(ranks=vae_ranks, backend=backend)
# adapted from https://github.com/feifeibear/long-context-attention/blob/main/yunchang/globals.py
def set_seq_parallel_pg(
sp_ulysses_degree: int,
@@ -658,7 +629,6 @@ def initialize_model_parallel(
ring_degree: int = 1,
tensor_parallel_size: int = 1,
pipeline_parallel_size: int = 1,
vae_parallel_size: int = 0,
backend: str | None = None,
) -> None:
if backend is None:
@@ -802,8 +772,6 @@ def initialize_model_parallel(
backend=backend,
parallel_mode="tensor",
)
if vae_parallel_size > 0:
init_vae_group(dit_parallel_size, vae_parallel_size, backend)
init_dit_group(dit_parallel_size, backend)
@@ -833,11 +801,6 @@ def destroy_model_parallel():
_PP.destroy()
_PP = None
global _VAE
if _VAE:
_VAE.destroy()
_VAE = None
def destroy_distributed_environment():
global _WORLD
@@ -0,0 +1,477 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Distributed VAE patch/tile parallelism utilities."""
from __future__ import annotations
import math
from collections.abc import Callable
from typing import Any
import torch
import torch.distributed as dist
from vllm.logger import init_logger
logger = init_logger(__name__)
def _get_vae_spatial_scale_factor(vae: Any) -> int:
try:
block_out_channels = getattr(getattr(vae, "config", None), "block_out_channels", None)
if block_out_channels:
return 2 ** (len(block_out_channels) - 1)
except Exception:
pass
return 8
def _factor_pp_grid(pp_size: int) -> tuple[int, int]:
"""Pick a (rows, cols) grid whose product equals `pp_size`."""
if pp_size <= 1:
return (1, 1)
root = int(math.sqrt(pp_size))
for rows in range(root, 0, -1):
if pp_size % rows == 0:
return (rows, pp_size // rows)
return (1, pp_size)
def _get_world_rank_pp_size(
group: dist.ProcessGroup,
vae_patch_parallel_size: int,
) -> tuple[int, int, int]:
world_size = dist.get_world_size(group)
rank = dist.get_rank(group)
pp_size = min(int(vae_patch_parallel_size), int(world_size))
return world_size, rank, pp_size
def _get_vae_out_channels(vae: Any) -> int:
return int(getattr(getattr(vae, "config", None), "out_channels", 3))
def _get_vae_tile_params(vae: Any) -> tuple[int, float] | None:
tile_latent_min_size = getattr(vae, "tile_latent_min_size", None)
tile_overlap_factor = getattr(vae, "tile_overlap_factor", None)
if tile_latent_min_size is None or tile_overlap_factor is None:
return None
return int(tile_latent_min_size), float(tile_overlap_factor)
def _get_vae_tiling_params(vae: Any) -> tuple[int, float, int] | None:
tile_sample_min_size = getattr(vae, "tile_sample_min_size", None)
tile_params = _get_vae_tile_params(vae)
if tile_params is None or tile_sample_min_size is None:
return None
tile_latent_min_size, tile_overlap_factor = tile_params
return tile_latent_min_size, tile_overlap_factor, int(tile_sample_min_size)
def _distributed_tiled_decode(
*,
vae: Any,
orig_decode: Callable[..., Any],
z: torch.Tensor,
group: dist.ProcessGroup,
vae_patch_parallel_size: int,
) -> torch.Tensor:
"""Distributed version of diffusers AutoencoderKL.tiled_decode (decode only).
Each rank decodes a subset of tiles; rank0 gathers all tiles and performs the
original blend + stitch logic. Non-rank0 ranks return an empty tensor; callers
can broadcast the stitched result if needed.
"""
world_size, rank, pp_size = _get_world_rank_pp_size(group, vae_patch_parallel_size)
if pp_size <= 1:
return orig_decode(z, return_dict=False)[0]
tiling_params = _get_vae_tiling_params(vae)
if tiling_params is None:
return orig_decode(z, return_dict=False)[0]
tile_latent_min_size, tile_overlap_factor, tile_sample_min_size = tiling_params
overlap_size = int(tile_latent_min_size * (1 - tile_overlap_factor))
if overlap_size <= 0:
return orig_decode(z, return_dict=False)[0]
h_starts = list(range(0, z.shape[2], overlap_size))
w_starts = list(range(0, z.shape[3], overlap_size))
num_rows = len(h_starts)
num_cols = len(w_starts)
num_tiles = num_rows * num_cols
if num_tiles < 2:
return orig_decode(z, return_dict=False)[0]
blend_extent = int(tile_sample_min_size * tile_overlap_factor)
row_limit = int(tile_sample_min_size - blend_extent)
# Decide which ranks actively decode tiles.
active = rank < pp_size
local_tiles: list[torch.Tensor] = []
local_meta: list[tuple[int, int, int]] = []
tile_id = 0
for i in h_starts:
for j in w_starts:
# Offset assignment by 1 so rank0 avoids decoding the largest (tile_id=0) tile.
tile_rank = (tile_id + 1) % pp_size
if active and (tile_rank == rank):
tile = z[:, :, i : i + tile_latent_min_size, j : j + tile_latent_min_size]
if getattr(getattr(vae, "config", None), "use_post_quant_conv", False):
tile = vae.post_quant_conv(tile)
decoded = vae.decoder(tile)
local_tiles.append(decoded)
local_meta.append((tile_id, int(decoded.shape[-2]), int(decoded.shape[-1])))
tile_id += 1
# Gather per-rank tile counts.
count_tensor = torch.tensor([len(local_tiles)], device=z.device, dtype=torch.int64)
if rank == 0:
count_gather = [torch.empty_like(count_tensor) for _ in range(world_size)]
else:
count_gather = None
dist.gather(count_tensor, gather_list=count_gather, dst=0, group=group)
max_count = 0
if rank == 0:
counts = [int(t.item()) for t in count_gather] # type: ignore[arg-type]
max_count = max(counts) if counts else 0
max_count_tensor = torch.tensor([max_count], device=z.device, dtype=torch.int64)
dist.broadcast(max_count_tensor, src=0, group=group)
max_count = int(max_count_tensor.item())
out_channels = _get_vae_out_channels(vae)
# Prepare padded metadata + tiles for gather.
meta_tensor = torch.full((max_count, 3), -1, device=z.device, dtype=torch.int64)
tile_tensor = torch.zeros(
(max_count, z.shape[0], out_channels, tile_sample_min_size, tile_sample_min_size),
device=z.device,
dtype=z.dtype,
)
for idx, (tile_id, h, w) in enumerate(local_meta):
meta_tensor[idx, 0] = tile_id
meta_tensor[idx, 1] = h
meta_tensor[idx, 2] = w
tile_tensor[idx, :, :, :h, :w] = local_tiles[idx]
if rank == 0:
meta_gather = [torch.empty_like(meta_tensor) for _ in range(world_size)]
tile_gather = [torch.empty_like(tile_tensor) for _ in range(world_size)]
else:
meta_gather = None
tile_gather = None
dist.gather(meta_tensor, gather_list=meta_gather, dst=0, group=group)
dist.gather(tile_tensor, gather_list=tile_gather, dst=0, group=group)
if rank != 0:
return torch.empty(0, device=z.device, dtype=z.dtype)
# Reconstruct the full tile grid on rank0.
tile_map: dict[int, torch.Tensor] = {}
for src_rank in range(world_size):
meta_src = meta_gather[src_rank] # type: ignore[index]
tiles_src = tile_gather[src_rank] # type: ignore[index]
for idx in range(max_count):
tid = int(meta_src[idx, 0].item())
if tid < 0:
continue
h = int(meta_src[idx, 1].item())
w = int(meta_src[idx, 2].item())
tile_map[tid] = tiles_src[idx, :, :, :h, :w]
rows: list[list[torch.Tensor]] = []
for r in range(num_rows):
row: list[torch.Tensor] = []
for c in range(num_cols):
tid = r * num_cols + c
row.append(tile_map[tid])
rows.append(row)
result_rows: list[torch.Tensor] = []
for i, row in enumerate(rows):
result_row: list[torch.Tensor] = []
for j, tile in enumerate(row):
if i > 0:
tile = vae.blend_v(rows[i - 1][j], tile, blend_extent)
if j > 0:
tile = vae.blend_h(row[j - 1], tile, blend_extent)
result_row.append(tile[:, :, :row_limit, :row_limit])
result_rows.append(torch.cat(result_row, dim=3))
return torch.cat(result_rows, dim=2)
def _distributed_patch_decode(
*,
vae: Any,
orig_decode: Callable[..., Any],
z: torch.Tensor,
group: dist.ProcessGroup,
vae_patch_parallel_size: int,
vae_scale_factor: int,
) -> torch.Tensor:
"""Decode one spatial block per rank, then stitch RGB blocks on rank0.
Intended for sizes where diffusers tiling would not kick in, so we can still
reduce the per-rank VAE decode activation peak. Each rank decodes a core
block with a small latent-space halo, then crops to the core and gathers the
RGB blocks to rank0 for final stitching.
"""
world_size, rank, pp_size = _get_world_rank_pp_size(group, vae_patch_parallel_size)
if pp_size <= 1:
return orig_decode(z, return_dict=False)[0]
tile_params = _get_vae_tile_params(vae)
if tile_params is None:
return orig_decode(z, return_dict=False)[0]
tile_latent_min_size, tile_overlap_factor = tile_params
overlap_latent = int(tile_latent_min_size * float(tile_overlap_factor))
halo_base = max(0, overlap_latent // 2)
# Only ranks < pp_size participate in decoding. Others send empty tensors.
active = rank < pp_size
bsz, _, latent_h, latent_w = z.shape
scale = int(vae_scale_factor)
out_h = latent_h * scale
out_w = latent_w * scale
out_channels = _get_vae_out_channels(vae)
local_core = torch.empty(0, device=z.device, dtype=z.dtype)
local_h = 0
local_w = 0
grid_rows, grid_cols = _factor_pp_grid(pp_size)
if active:
patch_idx = rank
patch_row = patch_idx // grid_cols
patch_col = patch_idx % grid_cols
h0 = (patch_row * latent_h) // grid_rows
h1 = ((patch_row + 1) * latent_h) // grid_rows
w0 = (patch_col * latent_w) // grid_cols
w1 = ((patch_col + 1) * latent_w) // grid_cols
core_h = max(0, h1 - h0)
core_w = max(0, w1 - w0)
if core_h == 0 or core_w == 0:
local_core = torch.empty(0, device=z.device, dtype=z.dtype)
else:
halo = max(halo_base, min(core_h, core_w) // 2)
ph0 = max(0, h0 - halo)
ph1 = min(latent_h, h1 + halo)
pw0 = max(0, w0 - halo)
pw1 = min(latent_w, w1 + halo)
tile = z[:, :, ph0:ph1, pw0:pw1]
if getattr(getattr(vae, "config", None), "use_post_quant_conv", False):
tile = vae.post_quant_conv(tile)
decoded = vae.decoder(tile)
ch0 = (h0 - ph0) * scale
cw0 = (w0 - pw0) * scale
ch1 = ch0 + core_h * scale
cw1 = cw0 + core_w * scale
local_core = decoded[:, :, ch0:ch1, cw0:cw1]
local_h = int(local_core.shape[-2]) if local_core.numel() else 0
local_w = int(local_core.shape[-1]) if local_core.numel() else 0
# Gather block shapes.
shape_tensor = torch.tensor([local_h, local_w], device=z.device, dtype=torch.int64)
if rank == 0:
shape_gather = [torch.empty_like(shape_tensor) for _ in range(world_size)]
else:
shape_gather = None
dist.gather(shape_tensor, gather_list=shape_gather, dst=0, group=group)
max_h = 0
max_w = 0
if rank == 0:
shapes = [tuple(int(x.item()) for x in t) for t in shape_gather] # type: ignore[arg-type]
max_h = max((h for h, _ in shapes), default=0)
max_w = max((w for _, w in shapes), default=0)
max_hw_tensor = torch.tensor([max_h, max_w], device=z.device, dtype=torch.int64)
dist.broadcast(max_hw_tensor, src=0, group=group)
max_h = int(max_hw_tensor[0].item())
max_w = int(max_hw_tensor[1].item())
# Pad local block for gather.
if max_h == 0 or max_w == 0:
padded = torch.empty(0, device=z.device, dtype=z.dtype)
else:
padded = torch.zeros((bsz, out_channels, max_h, max_w), device=z.device, dtype=z.dtype)
if local_h and local_w:
padded[:, :, :local_h, :local_w] = local_core
if rank == 0:
block_gather = [torch.empty_like(padded) for _ in range(world_size)]
else:
block_gather = None
dist.gather(padded, gather_list=block_gather, dst=0, group=group)
if rank != 0:
return torch.empty(0, device=z.device, dtype=z.dtype)
# Stitch on rank0.
out = torch.empty((bsz, out_channels, out_h, out_w), device=z.device, dtype=z.dtype)
for patch_idx in range(pp_size):
src_rank = patch_idx
patch_row = patch_idx // grid_cols
patch_col = patch_idx % grid_cols
h0 = (patch_row * latent_h) // grid_rows
h1 = ((patch_row + 1) * latent_h) // grid_rows
w0 = (patch_col * latent_w) // grid_cols
w1 = ((patch_col + 1) * latent_w) // grid_cols
ph = (h1 - h0) * scale
pw = (w1 - w0) * scale
if ph <= 0 or pw <= 0:
continue
tile = block_gather[src_rank] # type: ignore[index]
out[:, :, h0 * scale : h1 * scale, w0 * scale : w1 * scale] = tile[:, :, :ph, :pw]
return out
class VaePatchParallelism:
"""Patch/tile-parallel VAE decode wrapper.
This is meant to wrap `vae.decode` as an instance-level override
so pipelines don't need model-specific code paths.
"""
def __init__(
self,
vae: Any,
*,
vae_patch_parallel_size: int,
group_getter: Callable[[], dist.ProcessGroup],
) -> None:
self._vae = vae
self._vae_patch_parallel_size = int(vae_patch_parallel_size)
self._group_getter = group_getter
self._vae_scale_factor = _get_vae_spatial_scale_factor(vae)
self._orig_decode = vae.decode
def decode(self, z: torch.Tensor, return_dict: bool = True, *args: Any, **kwargs: Any):
# Keep the original path for unsupported VAE types / shapes.
if z.ndim != 4:
return self._orig_decode(z, return_dict=return_dict, *args, **kwargs)
if self._vae_patch_parallel_size <= 1 or not dist.is_initialized():
return self._orig_decode(z, return_dict=return_dict, *args, **kwargs)
if not getattr(self._vae, "use_tiling", False):
return self._orig_decode(z, return_dict=return_dict, *args, **kwargs)
try:
group = self._group_getter()
except Exception:
return self._orig_decode(z, return_dict=return_dict, *args, **kwargs)
world_size = dist.get_world_size(group)
rank = dist.get_rank(group)
pp_size = min(int(self._vae_patch_parallel_size), int(world_size))
if pp_size <= 1:
return self._orig_decode(z, return_dict=return_dict, *args, **kwargs)
# Match diffusers' condition for when VAE tiling would be used.
tile_latent_min_size = getattr(self._vae, "tile_latent_min_size", None)
if tile_latent_min_size is None:
decoded = _distributed_tiled_decode(
vae=self._vae,
orig_decode=self._orig_decode,
z=z,
group=group,
vae_patch_parallel_size=pp_size,
)
else:
should_tile = (z.shape[-1] > tile_latent_min_size) or (z.shape[-2] > tile_latent_min_size)
if should_tile:
decoded = _distributed_tiled_decode(
vae=self._vae,
orig_decode=self._orig_decode,
z=z,
group=group,
vae_patch_parallel_size=pp_size,
)
else:
decoded = _distributed_patch_decode(
vae=self._vae,
orig_decode=self._orig_decode,
z=z,
group=group,
vae_patch_parallel_size=pp_size,
vae_scale_factor=self._vae_scale_factor,
)
if rank == 0 and decoded.numel() == 0:
logger.warning("VAE patch parallel decode produced empty output on rank0; falling back to vae.decode.")
decoded = self._orig_decode(z, return_dict=False, *args, **kwargs)[0]
if rank == 0 and decoded.dtype != z.dtype:
decoded = decoded.to(dtype=z.dtype)
if rank == 0 and not decoded.is_contiguous():
decoded = decoded.contiguous()
shape_tensor = torch.empty((4,), device=z.device, dtype=torch.int64)
if rank == 0:
shape_tensor.copy_(torch.tensor(tuple(decoded.shape), device=z.device, dtype=torch.int64))
dist.broadcast(shape_tensor, src=0, group=group)
if rank != 0:
decoded = torch.empty(tuple(int(x) for x in shape_tensor.tolist()), device=z.device, dtype=z.dtype)
dist.broadcast(decoded, src=0, group=group)
if not return_dict:
return (decoded,)
from diffusers.models.autoencoders.vae import DecoderOutput
return DecoderOutput(sample=decoded)
def maybe_wrap_vae_decode_with_patch_parallelism(
pipeline: Any,
*,
vae_patch_parallel_size: int,
group_getter: Callable[[], dist.ProcessGroup],
) -> None:
"""Wrap a diffusers-style pipeline's `vae.decode` with patch/tile parallel decode."""
if vae_patch_parallel_size <= 1:
return
vae = getattr(pipeline, "vae", None)
if vae is None or not hasattr(vae, "decode"):
return
try:
from diffusers.models.autoencoders import AutoencoderKL
except Exception:
return
if not isinstance(vae, AutoencoderKL):
return
if getattr(vae, "_vllm_vae_patch_parallel_installed", False):
return
wrapper = VaePatchParallelism(
vae,
vae_patch_parallel_size=vae_patch_parallel_size,
group_getter=group_getter,
)
vae._vllm_vae_patch_parallel_installed = True # type: ignore[attr-defined]
vae._vllm_vae_patch_parallel_original_decode = vae.decode # type: ignore[attr-defined]
vae.decode = wrapper.decode # type: ignore[assignment]
@@ -8,6 +8,7 @@
# available at https://github.com/huggingface/transformers/blob/main/LICENSE.
import math
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any
@@ -17,13 +18,18 @@ from torch import nn
from torch.nn.attention.flex_attention import flex_attention
from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
from transformers.models.qwen2.modeling_qwen2 import (
Qwen2Attention,
Qwen2MLP,
Qwen2PreTrainedModel,
Qwen2RMSNorm,
Qwen2RotaryEmbedding,
)
from transformers.utils import ModelOutput
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
QKVParallelLinear,
RowParallelLinear,
)
from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.transformers_utils.configs.bagel import BagelConfig
from vllm.vllm_flash_attn import flash_attn_varlen_func
@@ -53,17 +59,105 @@ def patchify(imgs, p):
class MLPconnector(nn.Module):
def __init__(self, input_dim, output_dim, activation="gelu_pytorch_tanh"):
super().__init__()
self.fc1 = nn.Linear(input_dim, output_dim)
self.fc1 = ColumnParallelLinear(input_dim, output_dim, bias=True, gather_output=False)
if activation == "gelu":
self.act = nn.GELU()
elif activation == "gelu_pytorch_tanh":
self.act = nn.GELU(approximate="tanh")
else:
self.act = nn.ReLU()
self.fc2 = nn.Linear(output_dim, output_dim)
self.fc2 = RowParallelLinear(output_dim, output_dim, bias=True, input_is_parallel=True)
def forward(self, x):
return self.fc2(self.act(self.fc1(x)))
x_parallel, _ = self.fc1(x)
x_parallel = self.act(x_parallel)
return self.fc2(x_parallel)[0]
class BagelRotaryEmbedding(nn.Module):
"""Standalone rotary embedding that generates cos/sin from position ids.
Replaces HuggingFace's Qwen2RotaryEmbedding while preserving full
``rope_scaling`` support. When ``config.rope_scaling`` is set (e.g.
linear, dynamic-NTK, YaRN, …), we delegate the ``inv_freq`` /
``attention_scaling`` computation to HF's ``ROPE_INIT_FUNCTIONS`` so
that the frequency basis and scaling factor are identical to the
original checkpoint. This module has no learnable parameters.
"""
def __init__(self, config):
super().__init__()
if config.rope_scaling is not None:
# Delegate to HF's rope-scaling helpers for non-default types.
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type", "default"))
rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
inv_freq, self.attention_scaling = rope_init_fn(config, device=None)
else:
dim = config.hidden_size // config.num_attention_heads
inv_freq = 1.0 / (config.rope_theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
self.attention_scaling = 1.0
self.register_buffer("inv_freq", inv_freq, persistent=False)
@torch.no_grad()
def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Generate cos/sin embeddings for given position ids.
Args:
x: Input tensor (only used for dtype inference).
position_ids: Position indices, shape (batch_size, seq_len).
Returns:
cos, sin: Rotary embeddings, each of shape (batch_size, seq_len, dim).
"""
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
class BagelMLP(nn.Module):
def __init__(
self,
hidden_size: int,
intermediate_size: int,
hidden_act: str = "silu",
) -> None:
super().__init__()
self.gate_proj = ColumnParallelLinear(
hidden_size,
intermediate_size,
bias=False,
gather_output=False,
)
self.up_proj = ColumnParallelLinear(
hidden_size,
intermediate_size,
bias=False,
gather_output=False,
)
self.down_proj = RowParallelLinear(
intermediate_size,
hidden_size,
input_is_parallel=True,
bias=False,
)
if hidden_act != "silu":
raise ValueError(f"Unsupported activation: {hidden_act}. Only silu is supported.")
self.act_fn = nn.SiLU()
def forward(self, x):
gate, _ = self.gate_proj(x)
up, _ = self.up_proj(x)
x = self.act_fn(gate) * up
x, _ = self.down_proj(x)
return x
torch._dynamo.config.cache_size_limit = 512
@@ -157,24 +251,69 @@ class BaseNavitOutputWithPast(ModelOutput):
past_key_values: NaiveCache | None = None
class PackedAttentionMoT(Qwen2Attention):
class PackedAttentionMoT(nn.Module):
"""Packed attention with Mixture-of-Tokens routing for understanding/generation.
Uses vLLM's QKVParallelLinear and RowParallelLinear for tensor parallelism
support, following the same pattern as vLLM's Qwen2Attention.
The q/k/v projections are stacked into a single QKVParallelLinear:
- qkv_proj : stacks q_proj + k_proj + v_proj (understanding + gen text)
- qkv_proj_moe_gen : stacks q_proj_moe_gen + k_proj_moe_gen + v_proj_moe_gen (gen vae)
"""
def __init__(self, config, layer_idx: int | None = None):
super().__init__(config, layer_idx)
self.q_norm = Qwen2RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = Qwen2RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.q_norm_moe_gen = Qwen2RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm_moe_gen = Qwen2RMSNorm(self.head_dim, eps=config.rms_norm_eps)
super().__init__()
self.layer_idx = layer_idx
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.head_dim = config.hidden_size // config.num_attention_heads
head_dim = self.head_dim
self.q_proj_moe_gen = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=True)
self.k_proj_moe_gen = nn.Linear(config.hidden_size, config.num_key_value_heads * head_dim, bias=True)
self.v_proj_moe_gen = nn.Linear(config.hidden_size, config.num_key_value_heads * head_dim, bias=True)
self.o_proj_moe_gen = nn.Linear(config.num_attention_heads * head_dim, config.hidden_size, bias=False)
tp_size = get_tensor_model_parallel_world_size()
self.total_num_heads = config.num_attention_heads
assert self.total_num_heads % tp_size == 0
self.num_heads = self.total_num_heads // tp_size
self.total_num_kv_heads = config.num_key_value_heads
if self.total_num_kv_heads >= tp_size:
assert self.total_num_kv_heads % tp_size == 0
else:
assert tp_size % self.total_num_kv_heads == 0
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
self.head_dim = self.hidden_size // self.total_num_heads
self.q_size = self.num_heads * self.head_dim
self.kv_size = self.num_kv_heads * self.head_dim
# Understanding mode projections (stacked q/k/v)
self.qkv_proj = QKVParallelLinear(
self.hidden_size,
self.head_dim,
self.total_num_heads,
self.total_num_kv_heads,
bias=True,
)
self.o_proj = RowParallelLinear(
self.total_num_heads * self.head_dim,
self.hidden_size,
bias=False,
)
# Generation mode MoE projections (stacked q/k/v)
self.qkv_proj_moe_gen = QKVParallelLinear(
self.hidden_size,
self.head_dim,
self.total_num_heads,
self.total_num_kv_heads,
bias=True,
)
self.o_proj_moe_gen = RowParallelLinear(
self.total_num_heads * self.head_dim,
self.hidden_size,
bias=False,
)
# QK normalization
self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.q_norm_moe_gen = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm_moe_gen = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.rotary_op = RotaryEmbedding(is_neox_style=True)
@@ -194,38 +333,43 @@ class PackedAttentionMoT(Qwen2Attention):
packed_text_indexes=None,
):
if mode == "und":
packed_query_states = self.q_proj(packed_query_sequence).view(-1, self.num_heads, self.head_dim)
packed_key_states = self.k_proj(packed_query_sequence).view(-1, self.num_key_value_heads, self.head_dim)
packed_value_states = self.v_proj(packed_query_sequence).view(-1, self.num_key_value_heads, self.head_dim)
qkv, _ = self.qkv_proj(packed_query_sequence)
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
packed_query_states = q.view(-1, self.num_heads, self.head_dim)
packed_key_states = k.view(-1, self.num_kv_heads, self.head_dim)
packed_value_states = v.view(-1, self.num_kv_heads, self.head_dim)
packed_query_states = self.q_norm(packed_query_states)
packed_key_states = self.k_norm(packed_key_states)
elif mode == "gen":
packed_query_sequence = packed_query_sequence.to(torch.bfloat16)
packed_query_states = packed_query_sequence.new_zeros(
(packed_query_sequence.shape[0], self.num_heads * self.head_dim)
)
packed_key_states = packed_query_sequence.new_zeros(
(packed_query_sequence.shape[0], self.num_key_value_heads * self.head_dim)
)
packed_value_states = packed_query_sequence.new_zeros(
(packed_query_sequence.shape[0], self.num_key_value_heads * self.head_dim)
)
packed_text_query_sequence = packed_query_sequence[packed_text_indexes]
packed_vae_query_sequence = packed_query_sequence[packed_vae_token_indexes]
packed_query_states[packed_text_indexes] = self.q_proj(packed_text_query_sequence)
packed_query_states[packed_vae_token_indexes] = self.q_proj_moe_gen(packed_vae_query_sequence)
# Project text tokens through base qkv
text_qkv, _ = self.qkv_proj(packed_text_query_sequence)
text_q, text_k, text_v = text_qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
packed_key_states[packed_text_indexes] = self.k_proj(packed_text_query_sequence)
packed_key_states[packed_vae_token_indexes] = self.k_proj_moe_gen(packed_vae_query_sequence)
# Project vae tokens through moe_gen qkv
vae_qkv, _ = self.qkv_proj_moe_gen(packed_vae_query_sequence)
vae_q, vae_k, vae_v = vae_qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
packed_value_states[packed_text_indexes] = self.v_proj(packed_text_query_sequence)
packed_value_states[packed_vae_token_indexes] = self.v_proj_moe_gen(packed_vae_query_sequence)
# Merge into packed tensors
total_len = packed_query_sequence.shape[0]
packed_query_states = packed_query_sequence.new_zeros((total_len, self.q_size))
packed_key_states = packed_query_sequence.new_zeros((total_len, self.kv_size))
packed_value_states = packed_query_sequence.new_zeros((total_len, self.kv_size))
packed_query_states[packed_text_indexes] = text_q
packed_query_states[packed_vae_token_indexes] = vae_q
packed_key_states[packed_text_indexes] = text_k
packed_key_states[packed_vae_token_indexes] = vae_k
packed_value_states[packed_text_indexes] = text_v
packed_value_states[packed_vae_token_indexes] = vae_v
packed_query_states = packed_query_states.view(-1, self.num_heads, self.head_dim)
packed_key_states = packed_key_states.view(-1, self.num_key_value_heads, self.head_dim)
packed_value_states = packed_value_states.view(-1, self.num_key_value_heads, self.head_dim)
packed_key_states = packed_key_states.view(-1, self.num_kv_heads, self.head_dim)
packed_value_states = packed_value_states.view(-1, self.num_kv_heads, self.head_dim)
packed_query_states = packed_query_states.to(torch.float32)
packed_query_states[packed_text_indexes] = self.q_norm(packed_query_states[packed_text_indexes])
@@ -252,8 +396,8 @@ class PackedAttentionMoT(Qwen2Attention):
past_value_states = past_key_values.value_cache[self.layer_idx]
seqlens = sum(query_lens) + sum(key_values_lens)
merged_key_states = past_key_states.new_zeros(size=[seqlens, self.num_key_value_heads, self.head_dim])
merged_value_states = past_key_states.new_zeros(size=[seqlens, self.num_key_value_heads, self.head_dim])
merged_key_states = past_key_states.new_zeros(size=[seqlens, self.num_kv_heads, self.head_dim])
merged_value_states = past_key_states.new_zeros(size=[seqlens, self.num_kv_heads, self.head_dim])
merged_key_states[packed_query_indexes] = packed_key_states
merged_key_states[packed_key_value_indexes] = past_key_states
merged_value_states[packed_query_indexes] = packed_value_states
@@ -277,14 +421,16 @@ class PackedAttentionMoT(Qwen2Attention):
max_seqlen_k=max(key_values_lens).item(),
causal=is_causal,
)
packed_attn_output = packed_attn_output.reshape(-1, self.hidden_size)
packed_attn_output = packed_attn_output.reshape(-1, self.q_size)
if mode == "und":
packed_attn_output = self.o_proj(packed_attn_output)
packed_attn_output, _ = self.o_proj(packed_attn_output)
elif mode == "gen":
packed_attn_output[packed_text_indexes] = self.o_proj(packed_attn_output[packed_text_indexes])
packed_attn_output[packed_vae_token_indexes] = self.o_proj_moe_gen(
packed_attn_output[packed_vae_token_indexes]
)
text_out, _ = self.o_proj(packed_attn_output[packed_text_indexes])
vae_out, _ = self.o_proj_moe_gen(packed_attn_output[packed_vae_token_indexes])
full_output = text_out.new_zeros((packed_attn_output.shape[0], self.hidden_size))
full_output[packed_text_indexes] = text_out
full_output[packed_vae_token_indexes] = vae_out
packed_attn_output = full_output
if update_past_key_values:
past_key_values.key_cache[self.layer_idx] = merged_key_states
@@ -298,19 +444,19 @@ class Qwen2MoTDecoderLayer(nn.Module):
self,
config,
layer_idx: int | None = None,
attn_module: Qwen2Attention | None = PackedAttentionMoT,
attn_module: type[nn.Module] | None = PackedAttentionMoT,
):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = attn_module(config, layer_idx)
self.mlp = Qwen2MLP(config)
self.mlp_moe_gen = Qwen2MLP(config)
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.input_layernorm_moe_gen = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm_moe_gen = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.mlp = BagelMLP(config.hidden_size, config.intermediate_size, config.hidden_act)
self.mlp_moe_gen = BagelMLP(config.hidden_size, config.intermediate_size, config.hidden_act)
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.input_layernorm_moe_gen = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm_moe_gen = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
@@ -391,7 +537,7 @@ class Qwen2MoTModel(Qwen2PreTrainedModel):
self.vocab_size = config.vocab_size
self.use_moe = "Mo" in config.layer_module
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.embed_tokens = VocabParallelEmbedding(config.vocab_size, config.hidden_size)
self.layers = nn.ModuleList(
[
Qwen2MoTDecoderLayer(config, layer_idx, attn_module=PackedAttentionMoT)
@@ -399,10 +545,10 @@ class Qwen2MoTModel(Qwen2PreTrainedModel):
]
)
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
if self.use_moe:
self.norm_moe_gen = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = Qwen2RotaryEmbedding(config=config)
self.norm_moe_gen = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = BagelRotaryEmbedding(config=config)
# Initialize weights and apply final processing
self.post_init()
@@ -528,6 +674,50 @@ class Qwen2MoTForCausalLM(Qwen2PreTrainedModel):
return outputs
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load weights for vLLM parallel layers.
Handles stacked parameter remapping for QKVParallelLinear:
- q_proj, k_proj, v_proj -> qkv_proj (shard ids: q, k, v)
- q_proj_moe_gen, k_proj_moe_gen, v_proj_moe_gen -> qkv_proj_moe_gen
Other parallel layers (gate_proj, up_proj, down_proj, embed_tokens, etc.)
keep HF checkpoint names and use weight_loader for TP sharding.
"""
stacked_params_mapping = [
# (param_name, shard_name, shard_id)
# More specific _moe_gen patterns FIRST to avoid substring
# ambiguity (`.q_proj` is a substring of `.q_proj_moe_gen`).
(".qkv_proj_moe_gen", ".q_proj_moe_gen", "q"),
(".qkv_proj_moe_gen", ".k_proj_moe_gen", "k"),
(".qkv_proj_moe_gen", ".v_proj_moe_gen", "v"),
(".qkv_proj", ".q_proj", "q"),
(".qkv_proj", ".k_proj", "k"),
(".qkv_proj", ".v_proj", "v"),
]
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
for name, loaded_weight in weights:
for param_name, weight_name, shard_id in stacked_params_mapping:
if weight_name not in name:
continue
name = name.replace(weight_name, param_name)
param = params_dict.get(name)
if param is None:
break
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight, shard_id)
break
else:
param = params_dict.get(name)
if param is None:
continue
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)
loaded_params.add(name)
return loaded_params
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
grid_h = np.arange(grid_size, dtype=np.float32)
@@ -639,7 +829,7 @@ def get_flattened_position_ids_extrapolate(img_h, img_w, patch_size, max_num_pat
return pos_ids
class Bagel(torch.nn.Module):
class Bagel(nn.Module):
config_class = BagelConfig
base_model_prefix = "bagel"
@@ -402,7 +402,7 @@ class BagelPipeline(nn.Module):
)
# Fail fast with a clear error instead of CUDA gather OOB.
max_tid = int(generation_input["packed_text_ids"].max().item())
emb_n = int(self.language_model.model.embed_tokens.weight.shape[0])
emb_n = int(self.language_model.vocab_size)
if max_tid >= emb_n:
raise ValueError(
"Tokenizer/model vocab mismatch: max token id "
@@ -438,7 +438,7 @@ class BagelPipeline(nn.Module):
)
# Fail fast for special tokens used by the image path as well.
max_tid_img = int(generation_input["packed_text_ids"].max().item())
emb_n = int(self.language_model.model.embed_tokens.weight.shape[0])
emb_n = int(self.language_model.vocab_size)
if max_tid_img >= emb_n:
raise ValueError(
"Tokenizer/model vocab mismatch (image path): max token id "
@@ -483,6 +483,28 @@ class BagelPipeline(nn.Module):
allowed = set(state.keys())
shapes = {k: tuple(v.shape) for k, v in state.items()}
tp_aware_params = {name for name, p in self.named_parameters() if hasattr(p, "weight_loader")}
# Expand allowed/tp_aware_params with stacked param source names.
# QKVParallelLinear merges q_proj+k_proj+v_proj into qkv_proj; the
# checkpoint stores the original separate names. We must recognise
# those names so _filtered_weights does not drop them.
_stacked_expansions = [
(".qkv_proj", ".q_proj"),
(".qkv_proj", ".k_proj"),
(".qkv_proj", ".v_proj"),
(".qkv_proj_moe_gen", ".q_proj_moe_gen"),
(".qkv_proj_moe_gen", ".k_proj_moe_gen"),
(".qkv_proj_moe_gen", ".v_proj_moe_gen"),
]
stacked_source_names: set[str] = set()
for name in list(allowed):
for target_suffix, source_suffix in _stacked_expansions:
if target_suffix in name:
stacked_source_names.add(name.replace(target_suffix, source_suffix))
allowed.update(stacked_source_names)
tp_aware_params.update(stacked_source_names)
def _normalize_name(name: str) -> str:
# Common wrappers/prefixes in checkpoints.
for pfx in ("module.", "model."):
@@ -536,7 +558,7 @@ class BagelPipeline(nn.Module):
for cand in _iter_candidate_names(name):
if cand in allowed:
# Only accept if tensor shape matches target param/buffer shape.
if tuple(tensor.shape) == shapes.get(cand):
if tuple(tensor.shape) == shapes.get(cand) or cand in tp_aware_params:
picked = cand
break
else:
@@ -22,6 +22,7 @@ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5Tokeniz
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_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
@@ -129,9 +130,7 @@ def retrieve_timesteps(
return timesteps, num_inference_steps
class FluxPipeline(
nn.Module,
):
class FluxPipeline(nn.Module, CFGParallelMixin):
def __init__(
self,
*,
@@ -500,21 +499,23 @@ class FluxPipeline(
def diffuse(
self,
prompt_embeds,
pooled_prompt_embeds,
negative_prompt_embeds,
negative_pooled_prompt_embeds,
latents,
latent_image_ids,
text_ids,
negative_text_ids,
timesteps,
do_true_cfg,
guidance,
true_cfg_scale,
):
prompt_embeds: torch.Tensor,
pooled_prompt_embeds: torch.Tensor,
negative_prompt_embeds: torch.Tensor,
negative_pooled_prompt_embeds: torch.Tensor,
latents: torch.Tensor,
latent_image_ids: torch.Tensor,
text_ids: torch.Tensor,
negative_text_ids: torch.Tensor,
timesteps: torch.Tensor,
do_true_cfg: bool,
guidance: torch.Tensor,
true_cfg_scale: float,
cfg_normalize: bool = False,
) -> torch.Tensor:
"""Diffusion loop with optional image conditioning."""
self.scheduler.set_begin_index(0)
self.transformer.do_true_cfg = do_true_cfg
for i, t in enumerate(timesteps):
if self.interrupt:
continue
@@ -523,36 +524,46 @@ class FluxPipeline(
# broadcast to batch dimension and place on same device/dtype as latents
timestep = t.expand(latents.shape[0]).to(device=latents.device, dtype=latents.dtype)
self.transformer.do_true_cfg = do_true_cfg # used in teacache hook
# Forward pass for positive prompt (or unconditional if no CFG)
noise_pred = self.transformer(
hidden_states=latents,
timestep=timestep / 1000,
guidance=guidance,
pooled_projections=pooled_prompt_embeds,
encoder_hidden_states=prompt_embeds,
txt_ids=text_ids,
img_ids=latent_image_ids,
joint_attention_kwargs=self.joint_attention_kwargs,
return_dict=False,
)[0]
positive_kwargs = {
"hidden_states": latents,
"timestep": timestep / 1000,
"guidance": guidance,
"pooled_projections": pooled_prompt_embeds,
"encoder_hidden_states": prompt_embeds,
"txt_ids": text_ids,
"img_ids": latent_image_ids,
"joint_attention_kwargs": self.joint_attention_kwargs,
"return_dict": False,
}
# Forward pass for negative prompt (CFG)
if do_true_cfg:
neg_noise_pred = self.transformer(
hidden_states=latents,
timestep=timestep / 1000,
guidance=guidance,
pooled_projections=negative_pooled_prompt_embeds,
encoder_hidden_states=negative_prompt_embeds,
txt_ids=negative_text_ids,
img_ids=latent_image_ids,
joint_attention_kwargs=self.joint_attention_kwargs,
return_dict=False,
)[0]
noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
negative_kwargs = {
"hidden_states": latents,
"timestep": timestep / 1000,
"guidance": guidance,
"pooled_projections": negative_pooled_prompt_embeds,
"encoder_hidden_states": negative_prompt_embeds,
"txt_ids": negative_text_ids,
"img_ids": latent_image_ids,
"joint_attention_kwargs": self.joint_attention_kwargs,
"return_dict": False,
}
else:
negative_kwargs = None
# Predict noise with automatic CFG parallel handling
noise_pred = self.predict_noise_maybe_with_cfg(
do_true_cfg,
true_cfg_scale,
positive_kwargs,
negative_kwargs,
cfg_normalize,
)
# compute the previous noisy sample x_t -> x_t-1
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
return latents
def check_cfg_parallel_validity(self, true_cfg_scale: float, has_neg_prompt: bool):
@@ -613,6 +624,7 @@ class FluxPipeline(
req.sampling_params.guidance_scale if req.sampling_params.guidance_scale is not None else guidance_scale
)
generator = req.sampling_params.generator or generator
true_cfg_scale = req.sampling_params.true_cfg_scale or true_cfg_scale
num_images_per_prompt = (
req.sampling_params.num_outputs_per_prompt
if req.sampling_params.num_outputs_per_prompt > 0
@@ -723,6 +735,7 @@ class FluxPipeline(
do_true_cfg,
guidance,
true_cfg_scale,
cfg_normalize=False,
)
self._current_timestep = None
@@ -110,9 +110,9 @@ def get_qwen_image_edit_pre_process_func(
if image is not None and not (
isinstance(image, torch.Tensor) and len(image.shape) > 1 and image.shape[1] == latent_channels
):
image = image_processor.resize(image, height, width)
image = image_processor.resize(image, calculated_height, calculated_width)
prompt_image = image
image = image_processor.preprocess(image, height, width)
image = image_processor.preprocess(image, calculated_height, calculated_width)
image = image.unsqueeze(2)
# Store preprocessed image and prompt image in request
+39
View File
@@ -113,6 +113,11 @@ DiffusionModelRegistry = _ModelRegistry(
}
)
_VAE_PATCH_PARALLEL_ALLOWLIST = {
# Only enable for models we have validated end-to-end.
"ZImagePipeline",
}
def initialize_model(
od_config: OmniDiffusionConfig,
@@ -137,12 +142,46 @@ def initialize_model(
model_class = DiffusionModelRegistry._try_load_model_cls(od_config.model_class_name)
if model_class is not None:
model = model_class(od_config=od_config)
vae_pp_size = od_config.parallel_config.vae_patch_parallel_size
if vae_pp_size > 1 and od_config.model_class_name not in _VAE_PATCH_PARALLEL_ALLOWLIST:
logger.warning(
"vae_patch_parallel_size=%d is set but VAE patch parallelism is only enabled for %s; ignoring.",
vae_pp_size,
sorted(_VAE_PATCH_PARALLEL_ALLOWLIST),
)
if (
vae_pp_size > 1
and od_config.model_class_name in _VAE_PATCH_PARALLEL_ALLOWLIST
and not od_config.vae_use_tiling
):
logger.info(
"vae_patch_parallel_size=%d requires vae_use_tiling; automatically enabling it.",
vae_pp_size,
)
od_config.vae_use_tiling = True
# Configure VAE memory optimization settings from config
if hasattr(model.vae, "use_slicing"):
model.vae.use_slicing = od_config.vae_use_slicing
if hasattr(model.vae, "use_tiling"):
model.vae.use_tiling = od_config.vae_use_tiling
if (
vae_pp_size > 1
and hasattr(model, "vae")
and od_config.model_class_name in _VAE_PATCH_PARALLEL_ALLOWLIST
and od_config.vae_use_tiling
):
from vllm_omni.diffusion.distributed.parallel_state import get_dit_group
from vllm_omni.diffusion.distributed.vae_patch_parallel import maybe_wrap_vae_decode_with_patch_parallelism
maybe_wrap_vae_decode_with_patch_parallelism(
model,
vae_patch_parallel_size=vae_pp_size,
group_getter=get_dit_group,
)
# Apply sequence parallelism if enabled
# This follows diffusers' pattern where enable_parallelism() is called
# at model loading time, not inside individual model files
+5 -5
View File
@@ -18,13 +18,13 @@ def _looks_like_bagel(model_name: str) -> bool:
"""Best-effort detection for Bagel (non-diffusers) diffusion models."""
try:
cfg = get_hf_file_to_dict("config.json", model_name)
model_type = cfg.get("model_type")
if model_type == "bagel":
return True
architectures = cfg.get("architectures") or []
return "BagelForConditionalGeneration" in architectures
except Exception:
return False
model_type = cfg.get("model_type")
if model_type == "bagel":
return True
architectures = cfg.get("architectures") or []
return "BagelForConditionalGeneration" in architectures
@lru_cache
@@ -158,7 +158,13 @@ class DiffusionModelRunner:
self.kv_transfer_manager.receive_kv_cache(req, target_device=getattr(self.pipeline, "device", None))
if req.sampling_params.generator is None and req.sampling_params.seed is not None:
req.sampling_params.generator = torch.Generator(device=self.device).manual_seed(req.sampling_params.seed)
if req.sampling_params.generator_device is not None:
gen_device = req.sampling_params.generator_device
elif self.device.type == "cpu":
gen_device = "cpu"
else:
gen_device = self.device
req.sampling_params.generator = torch.Generator(device=gen_device).manual_seed(req.sampling_params.seed)
# Refresh cache context if needed
if (