[Core] Add batch parallel VAE decode (#8162)
Signed-off-by: QianCyrus <101633534+QianCyrus@users.noreply.github.com>
This commit is contained in:
1 parent
2bcd1e449a
commit
c2cd13c009
12 files changed
+460
-37
No files matched your search
@@ -317,6 +317,8 @@ class DiffusionParallelConfig:
|
||||
|
||||
- "tile": Patch/tile parallel decode (default). Each rank decodes a subset
|
||||
of spatial tiles and the results are stitched on rank 0.
|
||||
- "batch": Decode complete images on different ranks, preserving their
|
||||
batch order. Requires AutoencoderKL/Flux2 and DP/PP/CFG sizes of 1.
|
||||
- "spatial_shard_height": Spatially-sharded decode that splits decoder
|
||||
feature maps along height and exchanges halo rows around spatial
|
||||
convolutions.
|
||||
@@ -357,10 +359,14 @@ class DiffusionParallelConfig:
|
||||
assert self.allgather_degree > 0, "AllGather degree must be > 0"
|
||||
assert self.cfg_parallel_size > 0, "CFG parallel size must be > 0"
|
||||
assert self.vae_patch_parallel_size > 0, "VAE patch parallel size must be > 0"
|
||||
assert self.vae_parallel_mode in {"tile", "spatial_shard_height", "spatial_shard_width"}, (
|
||||
"vae_parallel_mode must be one of {'tile', 'spatial_shard_height', 'spatial_shard_width'}, "
|
||||
assert self.vae_parallel_mode in {"tile", "batch", "spatial_shard_height", "spatial_shard_width"}, (
|
||||
"vae_parallel_mode must be one of {'tile', 'batch', 'spatial_shard_height', 'spatial_shard_width'}, "
|
||||
f"but got {self.vae_parallel_mode!r}."
|
||||
)
|
||||
if self.vae_parallel_mode == "batch" and (
|
||||
self.data_parallel_size not in (None, 1) or self.pipeline_parallel_size != 1 or self.cfg_parallel_size != 1
|
||||
):
|
||||
raise ValueError("VAE batch parallel decode requires DP, PP, and CFG parallel sizes to be 1")
|
||||
if self.allgather_degree > 1:
|
||||
assert self.ulysses_degree == 1 and self.ring_degree == 1, (
|
||||
"AllGather-KV (allgather_degree>1) is mutually exclusive with Ulysses/Ring in v1. "
|
||||
@@ -478,6 +484,8 @@ class DiffusionParallelConfig:
|
||||
if world_size % non_dp_size != 0:
|
||||
raise ValueError(f"WORLD size ({world_size}) must be divisible by non-DP parallel size ({non_dp_size})")
|
||||
inferred_data_parallel_size = world_size // non_dp_size
|
||||
if self.vae_parallel_mode == "batch" and inferred_data_parallel_size != 1:
|
||||
raise ValueError("VAE batch parallel decode requires DP, PP, and CFG parallel sizes to be 1")
|
||||
if self.data_parallel_size is not None and self.data_parallel_size != inferred_data_parallel_size:
|
||||
raise ValueError(
|
||||
f"data_parallel_size ({self.data_parallel_size}) does not match WORLD-derived value "
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from diffusers.models.autoencoders import AutoencoderKL as Diffusers_AutoencoderKL
|
||||
from diffusers.models.autoencoders.vae import DecoderOutput
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor import (
|
||||
@@ -14,6 +16,11 @@ from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor impor
|
||||
GridSpec,
|
||||
TileTask,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_classifier_free_guidance_world_size,
|
||||
get_data_parallel_world_size,
|
||||
get_pipeline_parallel_world_size,
|
||||
)
|
||||
|
||||
# from vllm_omni.diffusion.models.nextstep_1_1.modeling_flux_vae import AutoencoderKL as Next_Step_AutoencoderKL
|
||||
|
||||
@@ -34,6 +41,49 @@ class DistributedAutoencoderKL_base(DistributedVaeMixin):
|
||||
model.init_distributed()
|
||||
return model
|
||||
|
||||
def batch_split(self, z: torch.Tensor) -> tuple[list[TileTask], GridSpec]:
|
||||
executor = self.distributed_executor
|
||||
num_chunks = min(z.shape[0], executor.parallel_size, executor.world_size)
|
||||
tasks = [
|
||||
TileTask(index, (index,), chunk, workload=chunk.shape[0])
|
||||
for index, chunk in enumerate(z.tensor_split(num_chunks, dim=0))
|
||||
]
|
||||
# The concrete diffusers base supplies dtype through the mixin MRO.
|
||||
output_dtype = (
|
||||
torch.get_autocast_dtype(z.device.type) if torch.is_autocast_enabled(z.device.type) else self.dtype # type: ignore[attr-defined]
|
||||
)
|
||||
return tasks, GridSpec(split_dims=(0,), grid_shape=(num_chunks,), output_dtype=output_dtype)
|
||||
|
||||
def batch_merge(self, coord_tensor_map: dict[tuple[int, ...], torch.Tensor], grid_spec: GridSpec) -> torch.Tensor:
|
||||
return torch.cat([coord_tensor_map[(index,)] for index in range(grid_spec.grid_shape[0])], dim=0)
|
||||
|
||||
def _batch_parallel_decode(self, z: torch.Tensor, return_dict: bool = True, *args: Any, **kwargs: Any):
|
||||
# Resolve the native decoder before defining the task callback. Calling
|
||||
# self.decode here would recursively enter the distributed path. The
|
||||
# concrete diffusers base supplies decode through the mixin MRO.
|
||||
native_decode = super().decode # type: ignore[misc]
|
||||
executor = self.distributed_executor
|
||||
if z.shape[0] <= 1 or min(executor.parallel_size, executor.world_size) <= 1 or not dist.is_initialized():
|
||||
return native_decode(z, return_dict, *args, **kwargs)
|
||||
if (
|
||||
get_data_parallel_world_size() > 1
|
||||
or get_pipeline_parallel_world_size() > 1
|
||||
or get_classifier_free_guidance_world_size() > 1
|
||||
):
|
||||
raise ValueError("VAE batch parallel decode requires DP, PP, and CFG parallel sizes to be 1")
|
||||
|
||||
def decode_chunk(task: TileTask) -> torch.Tensor:
|
||||
# Keep native slicing/tiling and decoder arguments for each complete
|
||||
# image chunk; only the batch dimension is distributed.
|
||||
return native_decode(task.tensor, False, *args, **kwargs)[0]
|
||||
|
||||
result = executor.execute(
|
||||
z,
|
||||
DistributedOperator(split=self.batch_split, exec=decode_chunk, merge=self.batch_merge),
|
||||
broadcast_result=True,
|
||||
)
|
||||
return DecoderOutput(sample=result) if return_dict else (result,)
|
||||
|
||||
def tile_split(self, z: torch.Tensor) -> tuple[list[TileTask], GridSpec]:
|
||||
# mostly copy from AutoencoderKL
|
||||
overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
|
||||
@@ -185,6 +235,8 @@ class DistributedAutoencoderKL_base(DistributedVaeMixin):
|
||||
# Normally, we should override tiled_decode. However, since we also need to
|
||||
# support the patch split strategy, we override decode instead.
|
||||
def decode(self, z: torch.Tensor, return_dict: bool = True, *args: Any, **kwargs: Any):
|
||||
if self.distributed_executor.parallel_mode == "batch":
|
||||
return self._batch_parallel_decode(z, return_dict, *args, **kwargs)
|
||||
if not self.is_distributed_enabled():
|
||||
return super().decode(z, return_dict=return_dict, *args, **kwargs)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from typing import Any
|
||||
|
||||
@@ -93,6 +93,8 @@ class DistributedAutoencoderKLFlux2(DistributedAutoencoderKL_base, AutoencoderKL
|
||||
return enc
|
||||
|
||||
def decode(self, z: torch.Tensor, return_dict: bool = True, *args: Any, **kwargs: Any):
|
||||
if self.distributed_executor.parallel_mode == "batch":
|
||||
return self._batch_parallel_decode(z, return_dict, *args, **kwargs)
|
||||
if not self.is_distributed_enabled():
|
||||
return super().decode(z, return_dict=return_dict, *args, **kwargs)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -177,8 +177,14 @@ class DistributedVaeMixin:
|
||||
self.distributed_executor.set_parallel_size(parallel_size, mode=mode)
|
||||
|
||||
def is_distributed_enabled(self) -> bool:
|
||||
"""Whether to use distributed tile/patch execution, not native tiling.
|
||||
|
||||
Batch decode has its own dispatch; in batch mode, encoding and each
|
||||
assigned image chunk keep the native tiling/slicing settings.
|
||||
"""
|
||||
if (
|
||||
self.distributed_executor.parallel_size <= 1
|
||||
or self.distributed_executor.parallel_mode == "batch"
|
||||
or not dist.is_initialized()
|
||||
or not getattr(self, "use_tiling", False)
|
||||
):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
#
|
||||
# Copyright 2025 Black Forest Labs and The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
@@ -36,6 +36,7 @@ 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.autoencoders.autoencoder_kl_flux2 import DistributedAutoencoderKLFlux2
|
||||
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
|
||||
@@ -247,8 +248,13 @@ class Flux2KleinPipeline(
|
||||
subfolder="tokenizer",
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
vae_class = (
|
||||
DistributedAutoencoderKLFlux2
|
||||
if od_config.parallel_config.vae_parallel_mode == "batch"
|
||||
else AutoencoderKLFlux2
|
||||
)
|
||||
self.vae = from_pretrained_with_prefetch(
|
||||
AutoencoderKLFlux2.from_pretrained,
|
||||
vae_class.from_pretrained,
|
||||
model,
|
||||
subfolder="vae",
|
||||
prefetch_list=flux2_subfolders,
|
||||
|
||||
@@ -10,6 +10,7 @@ from vllm.model_executor.models.registry import _LazyRegisteredModel, _ModelRegi
|
||||
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig, uses_diffusers_adapter
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl import DistributedAutoencoderKL_base
|
||||
from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor import DistributedVaeMixin
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelConfig, get_sp_plan_from_model
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context
|
||||
@@ -466,14 +467,19 @@ def initialize_model(
|
||||
model = model_class(od_config=od_config)
|
||||
|
||||
vae_pp_size = od_config.parallel_config.vae_patch_parallel_size
|
||||
vae_mode = od_config.parallel_config.vae_parallel_mode
|
||||
is_distributed_vae = hasattr(model, "vae") and isinstance(model.vae, DistributedVaeMixin)
|
||||
if vae_mode == "batch" and not isinstance(getattr(model, "vae", None), DistributedAutoencoderKL_base):
|
||||
raise ValueError(
|
||||
"VAE batch parallel decode requires DistributedAutoencoderKL or DistributedAutoencoderKLFlux2"
|
||||
)
|
||||
if vae_pp_size > 1 and not is_distributed_vae:
|
||||
logger.warning(
|
||||
"vae_patch_parallel_size=%d is set but VAE patch parallelism is NOT enabled for %s; ignoring.",
|
||||
vae_pp_size,
|
||||
od_config.model_class_name,
|
||||
)
|
||||
if vae_pp_size > 1 and is_distributed_vae and not od_config.vae_use_tiling:
|
||||
if vae_pp_size > 1 and is_distributed_vae and vae_mode != "batch" and not od_config.vae_use_tiling:
|
||||
logger.info(
|
||||
"vae_patch_parallel_size=%d requires vae_use_tiling; automatically enabling it.",
|
||||
vae_pp_size,
|
||||
@@ -487,7 +493,7 @@ def initialize_model(
|
||||
model.vae.use_tiling = od_config.vae_use_tiling
|
||||
|
||||
if is_distributed_vae:
|
||||
model.vae.set_parallel_size(vae_pp_size, mode=od_config.parallel_config.vae_parallel_mode)
|
||||
model.vae.set_parallel_size(vae_pp_size, mode=vae_mode)
|
||||
|
||||
# Apply sequence parallelism if enabled
|
||||
# This follows diffusers' pattern where enable_parallelism() is called
|
||||
|
||||
Reference in new issue
Block a user