[1/N] Stream Wan VAE chunks to the media consumer (#7016)

Signed-off-by: specture724 <specture724@gmail.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-09-08 07:41:13 +08:00
1 parent 3b335814cc
commit 6942a5b600
6 files changed
+744 -19

No files matched your search

@@ -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 contextlib import nullcontext
from typing import Any
@@ -9,6 +9,7 @@ import torch.distributed as dist
from diffusers.models.autoencoders import AutoencoderKLWan
from diffusers.models.autoencoders.autoencoder_kl_wan import unpatchify
from diffusers.models.autoencoders.vae import DecoderOutput
from diffusers.utils.accelerate_utils import apply_forward_hook
from vllm.logger import init_logger
from vllm_omni.diffusion.distributed.autoencoders import wan_spatial_shard
@@ -18,6 +19,7 @@ from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor impor
GridSpec,
TileTask,
)
from vllm_omni.diffusion.models.interface import DecodedChunkConsumer
from vllm_omni.platforms import current_omni_platform
logger = init_logger(__name__)
@@ -45,9 +47,133 @@ class OmniAutoencoderKLWan(AutoencoderKLWan):
return super().encode(x, return_dict=return_dict)
def decode(self, z: torch.Tensor, return_dict: bool = True):
"""Decode a Wan latent using the Diffusers-compatible full-tensor API."""
with self._execution_context():
return super().decode(z, return_dict=return_dict)
def _decode(self, z: torch.Tensor, return_dict: bool = True):
"""Decode one latent batch, preserving the parent Diffusers contract."""
_, _, _, height, width = z.shape
tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio
tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio
if getattr(self, "use_tiling", False) and (width > tile_latent_min_width or height > tile_latent_min_height):
return self.tiled_decode(z, return_dict=return_dict)
return self._decode_temporal(z, return_dict=return_dict)
@apply_forward_hook
def decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
"""Decode ``z`` while synchronously delivering temporal chunks.
The ordinary :meth:`decode` contract remains the Diffusers contract.
Chunk callbacks deliberately reject a sliced batch: Diffusers slices
each sample before decoding, while a streaming consumer needs a stable
batch ownership contract. Callers can disable ``use_slicing`` or
invoke this capability once per sample.
Every rank participating in distributed VAE execution must invoke this
method. Spatial-sharded execution invokes ``on_chunk`` only on the
output-owning rank. Chunks have shape ``(B, C, T, H, W)`` and
values clamped to ``[-1, 1]``. After a callback failure, remaining
chunks are decoded and discarded before the exception is re-raised.
"""
if not callable(on_chunk):
raise TypeError("on_chunk must be callable")
if getattr(self, "use_slicing", False) and z.shape[0] > 1:
raise ValueError(
"Wan chunked decode does not support use_slicing for batch size > 1; "
"disable VAE slicing or decode one sample at a time"
)
with self._execution_context():
self._decode_with_chunks(z, on_chunk=on_chunk)
def _decode_temporal(
self,
z: torch.Tensor,
*,
on_chunk: DecodedChunkConsumer | None = None,
return_dict: bool = True,
):
"""Decode the non-tiled temporal path, optionally streaming chunks."""
self.clear_cache()
callback_error: BaseException | None = None
try:
x = self.post_quant_conv(z)
decoded_chunks: list[torch.Tensor] = []
for i in range(z.shape[2]):
self._conv_idx = [0]
if i == 0:
chunk = self.decoder(
x[:, :, i : i + 1, :, :],
feat_cache=self._feat_map,
feat_idx=self._conv_idx,
first_chunk=True,
)
else:
chunk = self.decoder(
x[:, :, i : i + 1, :, :],
feat_cache=self._feat_map,
feat_idx=self._conv_idx,
)
if on_chunk is None:
decoded_chunks.append(chunk)
continue
if callback_error is None:
try:
if self.config.patch_size is not None:
chunk = unpatchify(chunk, patch_size=self.config.patch_size)
on_chunk(torch.clamp(chunk, min=-1.0, max=1.0))
except BaseException as exc:
# A previously installed spatial-shard decoder still
# runs collectives, even for latents below the tiling
# threshold. Drain before surfacing consumer failures.
callback_error = exc
del chunk
if callback_error is not None:
raise callback_error
if on_chunk is not None:
return None
out = torch.cat(decoded_chunks, dim=2)
if self.config.patch_size is not None:
out = unpatchify(out, patch_size=self.config.patch_size)
out = torch.clamp(out, min=-1.0, max=1.0)
if not return_dict:
return (out,)
return DecoderOutput(sample=out)
finally:
self.clear_cache()
@staticmethod
def _discard_decoded_chunk(_chunk: torch.Tensor) -> None:
"""Consume a non-owner rank's chunk without retaining its tensor."""
def _decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
"""Run the temporal streaming primitive without API or hook handling."""
distributed_enabled = False
if hasattr(self, "is_distributed_enabled"):
distributed_enabled = self.is_distributed_enabled()
if getattr(self, "use_tiling", False):
tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio
tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio
exceeds_tile = z.shape[-1] > tile_latent_min_width or z.shape[-2] > tile_latent_min_height
if exceeds_tile:
if distributed_enabled:
self._tiled_decode_with_chunks(z, on_chunk=on_chunk)
return
raise ValueError("Wan chunk callbacks are unsupported for spatial tiling")
callback = on_chunk
if distributed_enabled and dist.get_rank(group=self.distributed_executor.group) != 0:
callback = self._discard_decoded_chunk
self._decode_temporal(z, on_chunk=callback)
class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
@classmethod
@@ -78,7 +204,7 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
blend_height = self.tile_sample_min_height - tile_sample_stride_height
blend_width = self.tile_sample_min_width - tile_sample_stride_width
tiletask_list = []
tiletask_list: list[TileTask] = []
for i in range(0, height, tile_latent_stride_height):
for j in range(0, width, tile_latent_stride_width):
time_list = []
@@ -151,7 +277,7 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
blend_height = tile_latent_min_height - tile_latent_stride_height
blend_width = tile_latent_min_width - tile_latent_stride_width
tiletask_list = []
tiletask_list: list[TileTask] = []
temporal_compression = self.config.scale_factor_temporal
for i in range(0, height, tile_sample_stride_height):
for j in range(0, width, tile_sample_stride_width):
@@ -307,8 +433,10 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
if not self.is_distributed_enabled():
return super().tiled_decode(z, return_dict=return_dict)
if self._spatial_shard_decode_enabled(z):
spatial_shard_enabled = self._spatial_shard_decode_enabled(z)
if spatial_shard_enabled:
split_dim = self._spatial_shard_decode_split_dim()
assert split_dim is not None
logger.debug("Decode running with Wan VAE spatial_shard_%s mode", split_dim)
return wan_spatial_shard.spatial_shard_decode(
self,
@@ -329,6 +457,27 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
return DecoderOutput(sample=result)
def _tiled_decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
"""Decode tiled latents and deliver temporal chunks to ``on_chunk``."""
if not self.is_distributed_enabled():
raise ValueError("Wan chunk callbacks are unsupported for spatial tiling")
spatial_shard_enabled = self._spatial_shard_decode_enabled(z)
if not spatial_shard_enabled:
raise ValueError("Wan chunk callbacks require spatial-shard decode when tiling is enabled")
split_dim = self._spatial_shard_decode_split_dim()
assert split_dim is not None
logger.debug("Decode running with Wan VAE spatial_shard_%s mode", split_dim)
wan_spatial_shard.spatial_shard_decode(
self,
z,
group=self.distributed_executor.group,
return_dict=True,
split_dim=split_dim,
on_chunk=on_chunk,
)
def tiled_encode(self, x: torch.Tensor) -> torch.Tensor:
"""
Encode using distributed VAE executor.
@@ -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
#
# The halo-exchange spatial-parallel decode here is adapted from SGLang's
# spatial-parallel VAE decode
@@ -24,7 +24,7 @@ from contextlib import nullcontext
from contextvars import ContextVar
from dataclasses import dataclass
from types import MethodType
from typing import Any
from typing import Any, cast
import torch
import torch.distributed as dist
@@ -34,6 +34,8 @@ from diffusers.models.autoencoders.autoencoder_kl_wan import unpatchify
from diffusers.models.autoencoders.vae import DecoderOutput
from vllm.logger import init_logger
from vllm_omni.diffusion.models.interface import DecodedChunkConsumer
logger = init_logger(__name__)
@@ -644,7 +646,7 @@ def _replace_child(
)
return
if isinstance(child, nn.ZeroPad2d):
padding = tuple(int(p) for p in child.padding)
padding = cast(tuple[int, int, int, int], tuple(int(p) for p in child.padding))
module_padding = padding
if parent.__class__.__name__ == "Sequential":
# Let the following WanDistConv2d account for global after-edge
@@ -794,7 +796,8 @@ def spatial_shard_decode(
group: dist.ProcessGroup,
return_dict: bool = True,
split_dim: str = "height",
) -> DecoderOutput | tuple[torch.Tensor]:
on_chunk: DecodedChunkConsumer | None = None,
) -> DecoderOutput | tuple[torch.Tensor] | None:
install_wan_spatial_shard_decode(vae, group, split_dim=split_dim)
if z.shape[2] == 0:
@@ -806,6 +809,7 @@ def spatial_shard_decode(
produce_output = world_size <= 1 or rank == 0
vae.clear_cache()
callback_error: BaseException | None = None
try:
context = vae._execution_context() if hasattr(vae, "_execution_context") else nullcontext()
with context:
@@ -820,18 +824,33 @@ def spatial_shard_decode(
first_chunk=(i == 0),
)
if produce_output:
decoded_chunks.append(chunk)
if on_chunk is not None and callback_error is None:
try:
if vae.config.patch_size is not None:
chunk = unpatchify(chunk, patch_size=vae.config.patch_size)
on_chunk(torch.clamp(chunk, min=-1.0, max=1.0))
except BaseException as exc:
# Keep all ranks in the temporal collective loop;
# surface the callback failure only after decode.
callback_error = exc
elif on_chunk is None:
decoded_chunks.append(chunk)
del chunk
if produce_output:
if produce_output and on_chunk is None:
out = torch.cat(decoded_chunks, dim=2)
if vae.config.patch_size is not None:
out = unpatchify(out, patch_size=vae.config.patch_size)
out = torch.clamp(out, min=-1.0, max=1.0)
else:
out = z.new_zeros(0)
finally:
vae.clear_cache()
if callback_error is not None:
raise callback_error
if on_chunk is not None:
return None
if not produce_output:
out = z.new_zeros(0)
if not return_dict:
return (out,)
return DecoderOutput(sample=out)