[Perf][Hunyuan] Optimize for vae and patch_embed (#6306)
Signed-off-by: dengyunyang <584797741@qq.com>
This commit is contained in:
1 parent
cd3867c373
commit
8d34d3b5de
19 files changed
+1583
-218
No files matched your search
@@ -10,4 +10,8 @@ from vllm_omni.diffusion.models.hunyuan_image3.pipeline_hunyuan_image3 import (
|
||||
HunyuanImage3Pipeline,
|
||||
)
|
||||
|
||||
__all__ = ["HunyuanImage3Pipeline", "HunyuanImage3Model", "HunyuanImage3Text2ImagePipeline"]
|
||||
__all__ = [
|
||||
"HunyuanImage3Pipeline",
|
||||
"HunyuanImage3Model",
|
||||
"HunyuanImage3Text2ImagePipeline",
|
||||
]
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
@@ -15,6 +14,10 @@ from diffusers.utils.torch_utils import randn_tensor
|
||||
from einops import rearrange
|
||||
from torch import Tensor, nn
|
||||
|
||||
# ResnetBlock is platform-dispatched in the layers package __init__: CUDA gets a
|
||||
# fused GroupNorm+SiLU kernel, every other backend gets the plain PyTorch block.
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers import ResnetBlock
|
||||
|
||||
|
||||
class DiagonalGaussianDistribution:
|
||||
def __init__(self, parameters: torch.Tensor, deterministic: bool = False):
|
||||
@@ -53,10 +56,6 @@ class DecoderOutput(BaseOutput):
|
||||
posterior: DiagonalGaussianDistribution | None = None
|
||||
|
||||
|
||||
def swish(x: Tensor) -> Tensor:
|
||||
return x * torch.sigmoid(x)
|
||||
|
||||
|
||||
def forward_with_checkpointing(module, *inputs, use_checkpointing=False):
|
||||
def create_custom_forward(module):
|
||||
def custom_forward(*inputs):
|
||||
@@ -70,46 +69,6 @@ def forward_with_checkpointing(module, *inputs, use_checkpointing=False):
|
||||
return module(*inputs)
|
||||
|
||||
|
||||
class Conv3d(nn.Conv3d):
|
||||
"""
|
||||
Perform Conv3d on patches with numerical differences from nn.Conv3d within 1e-5.
|
||||
Only symmetric padding is supported.
|
||||
"""
|
||||
|
||||
def forward(self, input):
|
||||
B, C, T, H, W = input.shape
|
||||
memory_count = (C * T * H * W) * 2 / 1024**3
|
||||
if memory_count > 2:
|
||||
n_split = math.ceil(memory_count / 2)
|
||||
assert n_split >= 2
|
||||
chunks = torch.chunk(input, chunks=n_split, dim=-3)
|
||||
padded_chunks = []
|
||||
for i in range(len(chunks)):
|
||||
if self.padding[0] > 0:
|
||||
padded_chunk = F.pad(
|
||||
chunks[i],
|
||||
(0, 0, 0, 0, self.padding[0], self.padding[0]),
|
||||
mode="constant" if self.padding_mode == "zeros" else self.padding_mode,
|
||||
value=0,
|
||||
)
|
||||
if i > 0:
|
||||
padded_chunk[:, :, : self.padding[0]] = chunks[i - 1][:, :, -self.padding[0] :]
|
||||
if i < len(chunks) - 1:
|
||||
padded_chunk[:, :, -self.padding[0] :] = chunks[i + 1][:, :, : self.padding[0]]
|
||||
else:
|
||||
padded_chunk = chunks[i]
|
||||
padded_chunks.append(padded_chunk)
|
||||
padding_bak = self.padding
|
||||
self.padding = (0, self.padding[1], self.padding[2])
|
||||
outputs = []
|
||||
for i in range(len(padded_chunks)):
|
||||
outputs.append(super().forward(padded_chunks[i]))
|
||||
self.padding = padding_bak
|
||||
return torch.cat(outputs, dim=-3)
|
||||
else:
|
||||
return super().forward(input)
|
||||
|
||||
|
||||
class AttnBlock(nn.Module):
|
||||
"""Attention with torch sdpa implementation."""
|
||||
|
||||
@@ -119,10 +78,12 @@ class AttnBlock(nn.Module):
|
||||
|
||||
self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
||||
|
||||
self.q = Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
self.k = Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
self.v = Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
self.proj_out = Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
# The memory concern is already handled via VAE tiling,
|
||||
# so there's no need to chunk here — calling nn.Conv3d directly is fine.
|
||||
self.q = nn.Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
self.k = nn.Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
self.v = nn.Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
self.proj_out = nn.Conv3d(in_channels, in_channels, kernel_size=1)
|
||||
|
||||
def attention(self, h_: Tensor) -> Tensor:
|
||||
h_ = self.norm(h_)
|
||||
@@ -142,41 +103,12 @@ class AttnBlock(nn.Module):
|
||||
return x + self.proj_out(self.attention(x))
|
||||
|
||||
|
||||
class ResnetBlock(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int):
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
out_channels = in_channels if out_channels is None else out_channels
|
||||
self.out_channels = out_channels
|
||||
|
||||
self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
||||
self.conv1 = Conv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)
|
||||
self.conv2 = Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
if self.in_channels != self.out_channels:
|
||||
self.nin_shortcut = Conv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
||||
|
||||
def forward(self, x):
|
||||
h = x
|
||||
h = self.norm1(h)
|
||||
h = swish(h)
|
||||
h = self.conv1(h)
|
||||
|
||||
h = self.norm2(h)
|
||||
h = swish(h)
|
||||
h = self.conv2(h)
|
||||
|
||||
if self.in_channels != self.out_channels:
|
||||
x = self.nin_shortcut(x)
|
||||
return x + h
|
||||
|
||||
|
||||
class DownsampleDCAE(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, add_temporal_downsample: bool = True):
|
||||
super().__init__()
|
||||
factor = 2 * 2 * 2 if add_temporal_downsample else 1 * 2 * 2
|
||||
assert out_channels % factor == 0
|
||||
self.conv = Conv3d(in_channels, out_channels // factor, kernel_size=3, stride=1, padding=1)
|
||||
self.conv = nn.Conv3d(in_channels, out_channels // factor, kernel_size=3, stride=1, padding=1)
|
||||
|
||||
self.add_temporal_downsample = add_temporal_downsample
|
||||
self.group_size = factor * in_channels // out_channels
|
||||
@@ -196,7 +128,7 @@ class UpsampleDCAE(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int, add_temporal_upsample: bool = True):
|
||||
super().__init__()
|
||||
factor = 2 * 2 * 2 if add_temporal_upsample else 1 * 2 * 2
|
||||
self.conv = Conv3d(in_channels, out_channels * factor, kernel_size=3, stride=1, padding=1)
|
||||
self.conv = nn.Conv3d(in_channels, out_channels * factor, kernel_size=3, stride=1, padding=1)
|
||||
|
||||
self.add_temporal_upsample = add_temporal_upsample
|
||||
self.repeats = factor * out_channels // in_channels
|
||||
@@ -233,7 +165,7 @@ class Encoder(nn.Module):
|
||||
self.num_res_blocks = num_res_blocks
|
||||
|
||||
# downsampling
|
||||
self.conv_in = Conv3d(in_channels, block_out_channels[0], kernel_size=3, stride=1, padding=1)
|
||||
self.conv_in = nn.Conv3d(in_channels, block_out_channels[0], kernel_size=3, stride=1, padding=1)
|
||||
|
||||
self.down = nn.ModuleList()
|
||||
block_in = block_out_channels[0]
|
||||
@@ -265,7 +197,7 @@ class Encoder(nn.Module):
|
||||
|
||||
# end
|
||||
self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
|
||||
self.conv_out = Conv3d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1)
|
||||
self.conv_out = nn.Conv3d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1)
|
||||
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
@@ -291,7 +223,7 @@ class Encoder(nn.Module):
|
||||
group_size = self.block_out_channels[-1] // (2 * self.z_channels)
|
||||
shortcut = rearrange(h, "b (c r) f h w -> b c r f h w", r=group_size).mean(dim=2)
|
||||
h = self.norm_out(h)
|
||||
h = swish(h)
|
||||
h = F.silu(h)
|
||||
h = self.conv_out(h)
|
||||
h += shortcut
|
||||
return h
|
||||
@@ -321,7 +253,7 @@ class Decoder(nn.Module):
|
||||
|
||||
# z to block_in
|
||||
block_in = block_out_channels[0]
|
||||
self.conv_in = Conv3d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
|
||||
self.conv_in = nn.Conv3d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
|
||||
|
||||
# middle
|
||||
self.mid = nn.Module()
|
||||
@@ -351,7 +283,7 @@ class Decoder(nn.Module):
|
||||
|
||||
# end
|
||||
self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
|
||||
self.conv_out = Conv3d(block_in, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
self.conv_out = nn.Conv3d(block_in, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
@@ -376,7 +308,7 @@ class Decoder(nn.Module):
|
||||
|
||||
# end
|
||||
h = self.norm_out(h)
|
||||
h = swish(h)
|
||||
h = F.silu(h)
|
||||
h = self.conv_out(h)
|
||||
return h
|
||||
|
||||
|
||||
@@ -79,6 +79,13 @@ from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step
|
||||
from vllm_omni.diffusion.layers.fused_moe import FusedMoE
|
||||
from vllm_omni.diffusion.layers.norm import RMSNorm
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
|
||||
# ResBlock is platform-dispatched in the layers package __init__: CUDA gets
|
||||
# fused GroupNorm+SiLU and AdaGN kernels, every other backend gets the plain
|
||||
# PyTorch block. UNetDown and UNetUp below instantiate whichever one this
|
||||
# resolves to.
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers import ResBlock
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.common import conv_nd, normalization
|
||||
from vllm_omni.diffusion.utils.kv_utils import repeat_kv
|
||||
from vllm_omni.model_executor.layers.timestep_embedding import timestep_embedding
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -171,44 +178,6 @@ def real_batched_index_select(t, dim, idx):
|
||||
return torch.stack([torch.index_select(t[i], dim - 1, idx[i]) for i in range(len(t))])
|
||||
|
||||
|
||||
def conv_nd(dims, *args, **kwargs): # noqa: N802
|
||||
"""
|
||||
Create a 1D, 2D, or 3D convolution module.
|
||||
"""
|
||||
if dims == 1:
|
||||
return nn.Conv1d(*args, **kwargs)
|
||||
elif dims == 2:
|
||||
return nn.Conv2d(*args, **kwargs)
|
||||
elif dims == 3:
|
||||
return nn.Conv3d(*args, **kwargs)
|
||||
raise ValueError(f"unsupported dimensions: {dims}")
|
||||
|
||||
|
||||
def normalization(channels, **kwargs):
|
||||
"""
|
||||
Make a standard normalization layer.
|
||||
:param channels: number of input channels.
|
||||
:return: a nn.Module for normalization.
|
||||
"""
|
||||
return nn.GroupNorm(32, channels, **kwargs)
|
||||
|
||||
|
||||
def linear(*args, **kwargs):
|
||||
"""
|
||||
Create a linear module.
|
||||
"""
|
||||
return nn.Linear(*args, **kwargs)
|
||||
|
||||
|
||||
def zero_module(module):
|
||||
"""
|
||||
Zero out the parameters of a module and return it.
|
||||
"""
|
||||
for p in module.parameters():
|
||||
p.detach().zero_()
|
||||
return module
|
||||
|
||||
|
||||
def _to_tuple(x, dim=2):
|
||||
if isinstance(x, int):
|
||||
return (x,) * dim
|
||||
@@ -3282,99 +3251,6 @@ class TimestepEmbedder(nn.Module):
|
||||
return t_emb
|
||||
|
||||
|
||||
class ResBlock(nn.Module):
|
||||
r"""
|
||||
A residual block that can optionally change the number of channels.
|
||||
|
||||
Args:
|
||||
in_channels (`int`):
|
||||
The number of input channels.
|
||||
emb_channels (`int`):
|
||||
The number of timestep embedding channels.
|
||||
dropout (`float`):
|
||||
The rate of dropout.
|
||||
out_channels (`int`, *optional*):
|
||||
If specified, the number of output channels.
|
||||
use_conv (`bool`, *optional*):
|
||||
If True and out_channels is specified, use a spatial convolution instead of a
|
||||
smaller 1x1 convolution to change the channels in the skip connection.
|
||||
dims (`int`, *optional*):
|
||||
Determines if the signal is 1D, 2D, or 3D.
|
||||
up (`bool`, *optional*):
|
||||
If True, use this block for upsampling.
|
||||
down (`bool`, *optional*):
|
||||
If True, use this block for downsampling.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
emb_channels,
|
||||
out_channels=None,
|
||||
dropout=0.0,
|
||||
use_conv=False,
|
||||
dims=2,
|
||||
up=False,
|
||||
down=False,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
factory_kwargs = {"dtype": dtype, "device": device}
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
self.dropout = dropout
|
||||
self.out_channels = out_channels or self.in_channels
|
||||
self.use_conv = use_conv
|
||||
|
||||
self.in_layers = nn.Sequential(
|
||||
normalization(self.in_channels, **factory_kwargs),
|
||||
nn.SiLU(),
|
||||
conv_nd(dims, self.in_channels, self.out_channels, 3, padding=1, **factory_kwargs), # noqa: N802
|
||||
)
|
||||
|
||||
self.updown = up or down
|
||||
self.h_upd = self.x_upd = nn.Identity()
|
||||
|
||||
self.emb_layers = nn.Sequential(nn.SiLU(), linear(emb_channels, 2 * self.out_channels, **factory_kwargs))
|
||||
|
||||
self.out_layers = nn.Sequential(
|
||||
normalization(self.out_channels, **factory_kwargs),
|
||||
nn.SiLU(),
|
||||
nn.Dropout(p=dropout),
|
||||
zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1, **factory_kwargs)), # noqa: N802
|
||||
)
|
||||
|
||||
if self.out_channels == self.in_channels:
|
||||
self.skip_connection = nn.Identity()
|
||||
elif use_conv:
|
||||
self.skip_connection = conv_nd(dims, self.in_channels, self.out_channels, 3, padding=1, **factory_kwargs) # noqa: N802
|
||||
else:
|
||||
self.skip_connection = conv_nd(dims, self.in_channels, self.out_channels, 1, **factory_kwargs) # noqa: N802
|
||||
|
||||
def forward(self, x, emb) -> torch.Tensor:
|
||||
if self.updown:
|
||||
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
||||
h = in_rest(x)
|
||||
h = self.h_upd(h)
|
||||
x = self.x_upd(x)
|
||||
h = in_conv(h)
|
||||
else:
|
||||
h = self.in_layers(x)
|
||||
|
||||
emb_out = self.emb_layers(emb)
|
||||
while len(emb_out.shape) < len(h.shape):
|
||||
emb_out = emb_out[..., None]
|
||||
|
||||
# Adaptive Group Normalization
|
||||
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
||||
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
||||
h = out_norm(h) * (1.0 + scale) + shift
|
||||
h = out_rest(h)
|
||||
|
||||
return self.skip_connection(x) + h
|
||||
|
||||
|
||||
class UNetDown(nn.Module):
|
||||
def __init__(
|
||||
self, patch_size, in_channels, emb_channels, hidden_channels, out_channels, dropout=0.0, device=None, dtype=None
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Platform-dispatched layer implementations for HunyuanImage3.
|
||||
|
||||
The two blocks are selected by platform:
|
||||
|
||||
Layout::
|
||||
native/autoencoder_blocks.py default ResnetBlock
|
||||
native/transformer_blocks.py default ResBlock
|
||||
nvidia/autoencoder_blocks.py CUDA ResnetBlock (fused)
|
||||
nvidia/transformer_blocks.py CUDA ResBlock (fused)
|
||||
"""
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
if current_omni_platform.is_cuda():
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.nvidia import ResBlock, ResnetBlock
|
||||
else:
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.native import ResBlock, ResnetBlock
|
||||
|
||||
__all__ = ["ResBlock", "ResnetBlock"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from .utils import (
|
||||
conv_nd,
|
||||
linear,
|
||||
normalization,
|
||||
zero_module,
|
||||
)
|
||||
|
||||
__all__ = ["conv_nd", "linear", "normalization", "zero_module"]
|
||||
@@ -0,0 +1,51 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Small platform-agnostic helpers for UNet-style blocks (adapted from diffusers).
|
||||
|
||||
``conv_nd`` / ``normalization`` / ``linear`` / ``zero_module`` are used by the
|
||||
``ResBlock`` / ``UNetDown`` / ``UNetUp`` implementations across HunyuanImage3's
|
||||
platform-specific layer packages. They are plain ``nn.ConvNd`` / ``nn.GroupNorm``
|
||||
/ ``nn.Linear`` wrappers with no hardware-specific behaviour, so they live here
|
||||
instead of being duplicated per backend.
|
||||
"""
|
||||
|
||||
from torch import nn
|
||||
|
||||
|
||||
def conv_nd(dims, *args, **kwargs): # noqa: N802
|
||||
"""
|
||||
Create a 1D, 2D, or 3D convolution module.
|
||||
"""
|
||||
if dims == 1:
|
||||
return nn.Conv1d(*args, **kwargs)
|
||||
elif dims == 2:
|
||||
return nn.Conv2d(*args, **kwargs)
|
||||
elif dims == 3:
|
||||
return nn.Conv3d(*args, **kwargs)
|
||||
raise ValueError(f"unsupported dimensions: {dims}")
|
||||
|
||||
|
||||
def normalization(channels, **kwargs):
|
||||
"""
|
||||
Make a standard normalization layer.
|
||||
:param channels: number of input channels.
|
||||
:return: a nn.Module for normalization.
|
||||
"""
|
||||
return nn.GroupNorm(32, channels, **kwargs)
|
||||
|
||||
|
||||
def linear(*args, **kwargs):
|
||||
"""
|
||||
Create a linear module.
|
||||
"""
|
||||
return nn.Linear(*args, **kwargs)
|
||||
|
||||
|
||||
def zero_module(module):
|
||||
"""
|
||||
Zero out the parameters of a module and return it.
|
||||
"""
|
||||
for p in module.parameters():
|
||||
p.detach().zero_()
|
||||
return module
|
||||
@@ -0,0 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Native (plain PyTorch) layer implementations."""
|
||||
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.native.autoencoder_blocks import ResnetBlock
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.native.transformer_blocks import ResBlock
|
||||
|
||||
__all__ = ["ResBlock", "ResnetBlock"]
|
||||
@@ -0,0 +1,44 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""ResnetBlock for the HunyuanImage3 autoencoder — default fallback implementation.
|
||||
|
||||
Uses native PyTorch ``nn.GroupNorm`` + ``F.silu``. Hardware-specific optimized
|
||||
versions live in subdirectories (e.g., nvidia/) and are selected via __init__.py
|
||||
dispatch.
|
||||
"""
|
||||
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
|
||||
class ResnetBlock(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int):
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
out_channels = in_channels if out_channels is None else out_channels
|
||||
self.out_channels = out_channels
|
||||
|
||||
self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
||||
self.conv1 = nn.Conv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)
|
||||
self.conv2 = nn.Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
if self.in_channels != self.out_channels:
|
||||
self.nin_shortcut = nn.Conv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
||||
|
||||
def forward(self, x):
|
||||
h = x
|
||||
h = self.norm1(h)
|
||||
h = F.silu(h)
|
||||
h = self.conv1(h)
|
||||
|
||||
h = self.norm2(h)
|
||||
h = F.silu(h)
|
||||
h = self.conv2(h)
|
||||
|
||||
if self.in_channels != self.out_channels:
|
||||
x = self.nin_shortcut(x)
|
||||
return x + h
|
||||
|
||||
|
||||
__all__ = ["ResnetBlock"]
|
||||
@@ -0,0 +1,110 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""DiT ``ResBlock`` for HunyuanImage3 -- default implementation.
|
||||
|
||||
Plain PyTorch: ``GroupNorm -> SiLU`` runs as two ops and the adaptive
|
||||
GroupNorm as ``norm(h) * (1 + scale) + shift``. Hardware-specific variants
|
||||
live in sibling packages (e.g. ``nvidia/``) and are picked by the dispatch in
|
||||
``hunyuan_image3/__init__.py``.
|
||||
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.common import conv_nd, linear, normalization, zero_module
|
||||
|
||||
|
||||
class ResBlock(nn.Module):
|
||||
r"""
|
||||
A residual block that can optionally change the number of channels.
|
||||
Args:
|
||||
in_channels (`int`):
|
||||
The number of input channels.
|
||||
emb_channels (`int`):
|
||||
The number of timestep embedding channels.
|
||||
dropout (`float`):
|
||||
The rate of dropout.
|
||||
out_channels (`int`, *optional*):
|
||||
If specified, the number of output channels.
|
||||
use_conv (`bool`, *optional*):
|
||||
If True and out_channels is specified, use a spatial convolution instead of a
|
||||
smaller 1x1 convolution to change the channels in the skip connection.
|
||||
dims (`int`, *optional*):
|
||||
Determines if the signal is 1D, 2D, or 3D.
|
||||
up (`bool`, *optional*):
|
||||
If True, use this block for upsampling.
|
||||
down (`bool`, *optional*):
|
||||
If True, use this block for downsampling.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
emb_channels,
|
||||
out_channels=None,
|
||||
dropout=0.0,
|
||||
use_conv=False,
|
||||
dims=2,
|
||||
up=False,
|
||||
down=False,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
factory_kwargs = {"dtype": dtype, "device": device}
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
self.dropout = dropout
|
||||
self.out_channels = out_channels or self.in_channels
|
||||
self.use_conv = use_conv
|
||||
|
||||
self.in_layers = nn.Sequential(
|
||||
normalization(self.in_channels, **factory_kwargs),
|
||||
nn.SiLU(),
|
||||
conv_nd(dims, self.in_channels, self.out_channels, 3, padding=1, **factory_kwargs), # noqa: N802
|
||||
)
|
||||
|
||||
self.updown = up or down
|
||||
self.h_upd = self.x_upd = nn.Identity()
|
||||
|
||||
self.emb_layers = nn.Sequential(nn.SiLU(), linear(emb_channels, 2 * self.out_channels, **factory_kwargs))
|
||||
|
||||
self.out_layers = nn.Sequential(
|
||||
normalization(self.out_channels, **factory_kwargs),
|
||||
nn.SiLU(),
|
||||
nn.Dropout(p=dropout),
|
||||
zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1, **factory_kwargs)), # noqa: N802
|
||||
)
|
||||
|
||||
if self.out_channels == self.in_channels:
|
||||
self.skip_connection = nn.Identity()
|
||||
elif use_conv:
|
||||
self.skip_connection = conv_nd(dims, self.in_channels, self.out_channels, 3, padding=1, **factory_kwargs) # noqa: N802
|
||||
else:
|
||||
self.skip_connection = conv_nd(dims, self.in_channels, self.out_channels, 1, **factory_kwargs) # noqa: N802
|
||||
|
||||
def forward(self, x, emb) -> torch.Tensor:
|
||||
if self.updown:
|
||||
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
||||
h = in_rest(x)
|
||||
h = self.h_upd(h)
|
||||
x = self.x_upd(x)
|
||||
h = in_conv(h)
|
||||
else:
|
||||
h = self.in_layers(x)
|
||||
|
||||
emb_out = self.emb_layers(emb)
|
||||
while len(emb_out.shape) < len(h.shape):
|
||||
emb_out = emb_out[..., None]
|
||||
|
||||
# Adaptive Group Normalization
|
||||
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
||||
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
||||
h = out_norm(h) * (1.0 + scale) + shift
|
||||
h = out_rest(h)
|
||||
|
||||
return self.skip_connection(x) + h
|
||||
|
||||
|
||||
__all__ = ["ResBlock"]
|
||||
@@ -0,0 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""NVIDIA (CUDA) implementations."""
|
||||
|
||||
from .autoencoder_blocks import ResnetBlock # noqa: E402
|
||||
from .transformer_blocks import ResBlock # noqa: E402
|
||||
|
||||
__all__ = ["ResnetBlock", "ResBlock"]
|
||||
@@ -0,0 +1,27 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from contextlib import contextmanager
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@contextmanager
|
||||
def cudnn_settings(benchmark: bool, deterministic: bool):
|
||||
"""Temporarily set cuDNN backend flags, restoring the old values on exit.
|
||||
|
||||
Used to scope ``torch.backends.cudnn.benchmark``/``deterministic`` to the
|
||||
few blocks whose convolutions actually benefit from autotune, instead of
|
||||
setting them globally at import time (which would silently change every
|
||||
other model's conv behaviour in the same process).
|
||||
"""
|
||||
old_benchmark = torch.backends.cudnn.benchmark
|
||||
old_deterministic = torch.backends.cudnn.deterministic
|
||||
|
||||
torch.backends.cudnn.benchmark = benchmark
|
||||
torch.backends.cudnn.deterministic = deterministic
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
torch.backends.cudnn.benchmark = old_benchmark
|
||||
torch.backends.cudnn.deterministic = old_deterministic
|
||||
@@ -0,0 +1,56 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""ResnetBlock for the HunyuanImage3 autoencoder — NVIDIA CUDA + Triton implementation.
|
||||
|
||||
Split out from autoencoder.py because its ``GroupNorm -> SiLU`` pairs are served
|
||||
by :func:`fused_group_norm_silu`, a single Triton kernel that falls back to
|
||||
native ``F.silu(F.group_norm(...))`` when Triton is unavailable.
|
||||
"""
|
||||
|
||||
from torch import nn
|
||||
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.nvidia._cudnn import cudnn_settings
|
||||
from vllm_omni.model_executor.models.common.ops import fused_group_norm_silu
|
||||
|
||||
|
||||
class ResnetBlock(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int):
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
out_channels = in_channels if out_channels is None else out_channels
|
||||
self.out_channels = out_channels
|
||||
|
||||
self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
||||
self.conv1 = nn.Conv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)
|
||||
self.conv2 = nn.Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
if self.in_channels != self.out_channels:
|
||||
self.nin_shortcut = nn.Conv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
||||
|
||||
def forward(self, x):
|
||||
# cuDNN autotune is scoped to this block rather than set at import time.
|
||||
# These ResnetBlocks carry the bulk of the VAE's conv work: ~29 instances
|
||||
# x 2 convs across every resolution (up to the 1024x1024 decode), versus
|
||||
# the scattered convs left in autoencoder.py (AttnBlock's 1x1 at the
|
||||
# lowest-res mid, down/up-samplers, conv_in/out) whose activations are
|
||||
# negligible. A process-wide flag would instead silently change every
|
||||
# other model's conv behaviour in the same process.
|
||||
with cudnn_settings(benchmark=True, deterministic=True):
|
||||
h = x
|
||||
h = fused_group_norm_silu(
|
||||
h, self.norm1.weight, self.norm1.bias, num_groups=self.norm1.num_groups, eps=self.norm1.eps
|
||||
)
|
||||
h = self.conv1(h)
|
||||
|
||||
h = fused_group_norm_silu(
|
||||
h, self.norm2.weight, self.norm2.bias, num_groups=self.norm2.num_groups, eps=self.norm2.eps
|
||||
)
|
||||
h = self.conv2(h)
|
||||
|
||||
if self.in_channels != self.out_channels:
|
||||
x = self.nin_shortcut(x)
|
||||
return x + h
|
||||
|
||||
|
||||
__all__ = ["ResnetBlock"]
|
||||
@@ -0,0 +1,138 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""``ResBlock`` for HunyuanImage3 -- NVIDIA CUDA + Triton implementation.
|
||||
|
||||
Two fusions over the default block:
|
||||
|
||||
* ``in_layers``: ``GroupNorm -> SiLU`` becomes one :func:`fused_group_norm_silu`
|
||||
kernel instead of two ops.
|
||||
* ``out_layers``: ``GroupNorm -> adaptive modulation -> SiLU`` (i.e.
|
||||
``SiLU(norm(h) * (1 + scale) + shift)``) becomes one
|
||||
:func:`fused_adaptive_group_norm_silu` kernel instead of four.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.common import conv_nd, normalization, zero_module
|
||||
from vllm_omni.diffusion.models.hunyuan_image3.layers.nvidia._cudnn import cudnn_settings
|
||||
from vllm_omni.model_executor.models.common.ops import (
|
||||
fused_adaptive_group_norm_silu,
|
||||
fused_group_norm_silu,
|
||||
)
|
||||
|
||||
|
||||
class ResBlock(nn.Module):
|
||||
r"""
|
||||
A residual block that can optionally change the number of channels.
|
||||
Args:
|
||||
in_channels (`int`):
|
||||
The number of input channels.
|
||||
emb_channels (`int`):
|
||||
The number of timestep embedding channels.
|
||||
dropout (`float`):
|
||||
The rate of dropout.
|
||||
out_channels (`int`, *optional*):
|
||||
If specified, the number of output channels.
|
||||
use_conv (`bool`, *optional*):
|
||||
If True and out_channels is specified, use a spatial convolution instead of a
|
||||
smaller 1x1 convolution to change the channels in the skip connection.
|
||||
dims (`int`, *optional*):
|
||||
Determines if the signal is 1D, 2D, or 3D.
|
||||
up (`bool`, *optional*):
|
||||
If True, use this block for upsampling.
|
||||
down (`bool`, *optional*):
|
||||
If True, use this block for downsampling.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
emb_channels,
|
||||
out_channels=None,
|
||||
dropout=0.0,
|
||||
use_conv=False,
|
||||
dims=2,
|
||||
up=False,
|
||||
down=False,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
factory_kwargs = {"dtype": dtype, "device": device}
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
self.dropout = dropout
|
||||
self.out_channels = out_channels or self.in_channels
|
||||
self.use_conv = use_conv
|
||||
|
||||
self.in_layers = nn.Sequential(
|
||||
normalization(self.in_channels, **factory_kwargs),
|
||||
nn.SiLU(),
|
||||
conv_nd(dims, self.in_channels, self.out_channels, 3, padding=1, **factory_kwargs), # noqa: N802
|
||||
)
|
||||
|
||||
self.updown = up or down
|
||||
self.h_upd = self.x_upd = nn.Identity()
|
||||
|
||||
self.emb_layers = nn.Sequential(nn.SiLU(), nn.Linear(emb_channels, 2 * self.out_channels, **factory_kwargs))
|
||||
|
||||
self.out_layers = nn.Sequential(
|
||||
normalization(self.out_channels, **factory_kwargs),
|
||||
nn.SiLU(),
|
||||
nn.Dropout(p=dropout),
|
||||
zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1, **factory_kwargs)), # noqa: N802
|
||||
)
|
||||
|
||||
if self.out_channels == self.in_channels:
|
||||
self.skip_connection = nn.Identity()
|
||||
elif use_conv:
|
||||
self.skip_connection = conv_nd(dims, self.in_channels, self.out_channels, 3, padding=1, **factory_kwargs) # noqa: N802
|
||||
else:
|
||||
self.skip_connection = conv_nd(dims, self.in_channels, self.out_channels, 1, **factory_kwargs) # noqa: N802
|
||||
|
||||
def forward(self, x, emb) -> torch.Tensor:
|
||||
# cuDNN autotune is scoped to this block rather than set at import time.
|
||||
# The benchmark=True win is concentrated in the convolutions right here:
|
||||
# this ResBlock sits inside UNetDown/UNetUp (patch_embed / final_layer),
|
||||
# the heaviest conv users in the DiT. A process-wide flag would instead
|
||||
# silently change every other model's conv behaviour in the same process.
|
||||
with cudnn_settings(benchmark=True, deterministic=True):
|
||||
# ``in_layers``/``out_layers`` stay nn.Sequential and are indexed into
|
||||
# rather than unpacked into named submodules -- that is what keeps the
|
||||
# state_dict keys (``in_layers.0/.2``, ``out_layers.0/.3``) identical to
|
||||
# the unfused block, so checkpoints load unchanged.
|
||||
in_norm, in_conv = self.in_layers[0], self.in_layers[-1]
|
||||
|
||||
# GroupNorm -> SiLU, one kernel instead of two.
|
||||
h = fused_group_norm_silu(x, in_norm.weight, in_norm.bias, num_groups=in_norm.num_groups, eps=in_norm.eps)
|
||||
if self.updown:
|
||||
h = self.h_upd(h)
|
||||
x = self.x_upd(x)
|
||||
h = in_conv(h)
|
||||
|
||||
emb_out = self.emb_layers(emb)
|
||||
while len(emb_out.shape) < len(h.shape):
|
||||
emb_out = emb_out[..., None]
|
||||
|
||||
# Adaptive GroupNorm -> SiLU: GroupNorm -> mul -> add -> silu, one
|
||||
# kernel instead of four. The ``nn.SiLU`` at ``out_layers[1]`` is
|
||||
# skipped here but stays in the Sequential, so state_dict keys are
|
||||
# unchanged.
|
||||
out_norm, out_rest = self.out_layers[0], self.out_layers[2:]
|
||||
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
||||
h = fused_adaptive_group_norm_silu(
|
||||
h,
|
||||
out_norm.weight,
|
||||
out_norm.bias,
|
||||
scale,
|
||||
shift,
|
||||
num_groups=out_norm.num_groups,
|
||||
eps=out_norm.eps,
|
||||
)
|
||||
h = out_rest(h)
|
||||
|
||||
return self.skip_connection(x) + h
|
||||
|
||||
|
||||
__all__ = ["ResBlock"]
|
||||
Reference in new issue
Block a user