HunyuanVideo: A Systematic Framework For Large Video Generation Model
Formatting hyvideo/vae/unet_causal_3d_blocks.py
KimbingNg1f32fd3f448a
diff --git a/hyvideo/vae/unet_causal_3d_blocks.py b/hyvideo/vae/unet_causal_3d_blocks.pyindex bc02cab..864f2b1 100644--- a/hyvideo/vae/unet_causal_3d_blocks.py+++ b/hyvideo/vae/unet_causal_3d_blocks.py@@ -17,7 +17,7 @@## ==============================================================================-from typing import Optional, Tuple, Union+from typing import Optional, Tuple, Unionimport torchimport torch.nn.functional as F@@ -31,14 +31,12 @@ from diffusers.models.attention_processor import Attentionfrom diffusers.models.normalization import AdaGroupNormfrom diffusers.models.normalization import RMSNorm-logger = logging.get_logger(__name__) # pylint: disable=invalid-namedef prepare_causal_attention_mask(n_frame: int, n_hw: int, dtype, device, batch_size: int = None):seq_len = n_frame * n_hw- mask = torch.full((seq_len, seq_len), float(- "-inf"), dtype=dtype, device=device)+ mask = torch.full((seq_len, seq_len), float("-inf"), dtype=dtype, device=device)for i in range(seq_len):i_frame = i // n_hwmask[i, : (i_frame + 1) * n_hw] = 0@@ -66,12 +64,10 @@ class CausalConv3d(nn.Module):super().__init__()self.pad_mode = pad_mode- padding = (kernel_size // 2, kernel_size // 2, kernel_size //- 2, kernel_size // 2, kernel_size - 1, 0) # W, H, T+ padding = (kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size - 1, 0) # W, H, Tself.time_causal_padding = padding- self.conv = nn.Conv3d(chan_in, chan_out, kernel_size,- stride=stride, dilation=dilation, **kwargs)+ self.conv = nn.Conv3d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs)def forward(self, x):x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)@@ -119,12 +115,11 @@ class UpsampleCausal3D(nn.Module):conv = Noneif use_conv_transpose:- assert False, "Not Implement yet"+ raise NotImplementedErrorelif use_conv:if kernel_size is None:kernel_size = 3- conv = CausalConv3d(self.channels, self.out_channels,- kernel_size=kernel_size, bias=bias)+ conv = CausalConv3d(self.channels, self.out_channels, kernel_size=kernel_size, bias=bias)if name == "conv":self.conv = conv@@ -140,7 +135,7 @@ class UpsampleCausal3D(nn.Module):assert hidden_states.shape[1] == self.channelsif self.norm is not None:- assert False, "Not Implement yet"+ raise NotImplementedErrorif self.use_conv_transpose:return self.conv(hidden_states)@@ -158,18 +153,16 @@ class UpsampleCausal3D(nn.Module):# size and do not make use of `scale_factor=2`if self.interpolate:B, C, T, H, W = hidden_states.shape- first_h, other_h = hidden_states.split((1, T-1), dim=2)+ first_h, other_h = hidden_states.split((1, T - 1), dim=2)if output_size is None:if T > 1:- other_h = F.interpolate(- other_h, scale_factor=self.upsample_factor, mode="nearest")+ other_h = F.interpolate(other_h, scale_factor=self.upsample_factor, mode="nearest")first_h = first_h.squeeze(2)- first_h = F.interpolate(- first_h, scale_factor=self.upsample_factor[1:], mode="nearest")+ first_h = F.interpolate(first_h, scale_factor=self.upsample_factor[1:], mode="nearest")first_h = first_h.unsqueeze(2)else:- assert False, "Not Implement yet"+ raise NotImplementedErrorif T > 1:hidden_states = torch.cat((first_h, other_h), dim=2)@@ -244,8 +237,7 @@ class DownsampleCausal3D(nn.Module):assert hidden_states.shape[1] == self.channelsif self.norm is not None:- hidden_states = self.norm(- hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)+ hidden_states = self.norm(hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)assert hidden_states.shape[1] == self.channels@@ -302,44 +294,36 @@ class ResnetBlockCausal3D(nn.Module):groups_out = groupsif self.time_embedding_norm == "ada_group":- self.norm1 = AdaGroupNorm(- temb_channels, in_channels, groups, eps=eps)+ self.norm1 = AdaGroupNorm(temb_channels, in_channels, groups, eps=eps)elif self.time_embedding_norm == "spatial":self.norm1 = SpatialNorm(in_channels, temb_channels)else:- self.norm1 = torch.nn.GroupNorm(- num_groups=groups, num_channels=in_channels, eps=eps, affine=True)+ self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)- self.conv1 = CausalConv3d(- in_channels, out_channels, kernel_size=3, stride=1)+ self.conv1 = CausalConv3d(in_channels, out_channels, kernel_size=3, stride=1)if temb_channels is not None:if self.time_embedding_norm == "default":self.time_emb_proj = linear_cls(temb_channels, out_channels)elif self.time_embedding_norm == "scale_shift":- self.time_emb_proj = linear_cls(- temb_channels, 2 * out_channels)+ self.time_emb_proj = linear_cls(temb_channels, 2 * out_channels)elif self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":self.time_emb_proj = Noneelse:- raise ValueError(- f"unknown time_embedding_norm : {self.time_embedding_norm} ")+ raise ValueError(f"Unknown time_embedding_norm : {self.time_embedding_norm} ")else:self.time_emb_proj = Noneif self.time_embedding_norm == "ada_group":- self.norm2 = AdaGroupNorm(- temb_channels, out_channels, groups_out, eps=eps)+ self.norm2 = AdaGroupNorm(temb_channels, out_channels, groups_out, eps=eps)elif self.time_embedding_norm == "spatial":self.norm2 = SpatialNorm(out_channels, temb_channels)else:- self.norm2 = torch.nn.GroupNorm(- num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)+ self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)self.dropout = torch.nn.Dropout(dropout)conv_3d_out_channels = conv_3d_out_channels or out_channels- self.conv2 = CausalConv3d(- out_channels, conv_3d_out_channels, kernel_size=3, stride=1)+ self.conv2 = CausalConv3d(out_channels, conv_3d_out_channels, kernel_size=3, stride=1)self.nonlinearity = get_activation(non_linearity)@@ -347,8 +331,7 @@ class ResnetBlockCausal3D(nn.Module):if self.up:self.upsample = UpsampleCausal3D(in_channels, use_conv=False)elif self.down:- self.downsample = DownsampleCausal3D(- in_channels, use_conv=False, name="op")+ self.downsample = DownsampleCausal3D(in_channels, use_conv=False, name="op")self.use_in_shortcut = self.in_channels != conv_3d_out_channels if use_in_shortcut is None else use_in_shortcut@@ -427,8 +410,7 @@ class ResnetBlockCausal3D(nn.Module):self.conv_shortcut(input_tensor))- output_tensor = (input_tensor + hidden_states) / \- self.output_scale_factor+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factorreturn output_tensor@@ -468,8 +450,7 @@ def get_down_block3d()attention_head_dim = num_attention_heads- down_block_type = down_block_type[7:] if down_block_type.startswith(- "UNetRes") else down_block_type+ down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_typeif down_block_type == "DownEncoderBlockCausal3D":return DownEncoderBlockCausal3D(num_layers=num_layers,@@ -523,8 +504,7 @@ def get_up_block3d()attention_head_dim = num_attention_heads- up_block_type = up_block_type[7:] if up_block_type.startswith(- "UNetRes") else up_block_type+ up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_typeif up_block_type == "UpDecoderBlockCausal3D":return UpDecoderBlockCausal3D(num_layers=num_layers,@@ -565,8 +545,7 @@ class UNetMidBlockCausal3D(nn.Module):output_scale_factor: float = 1.0,):super().__init__()- resnet_groups = resnet_groups if resnet_groups is not None else min(- in_channels // 4, 32)+ resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)self.add_attention = add_attentionif attn_groups is None:@@ -597,7 +576,6 @@ class UNetMidBlockCausal3D(nn.Module):for _ in range(num_layers):if self.add_attention:- # assert False, "Not implemented yet"attentions.append(Attention(in_channels,@@ -639,14 +617,12 @@ class UNetMidBlockCausal3D(nn.Module):for attn, resnet in zip(self.attentions, self.resnets[1:]):if attn is not None:B, C, T, H, W = hidden_states.shape- hidden_states = rearrange(- hidden_states, "b c f h w -> b (f h w) c")+ hidden_states = rearrange(hidden_states, "b c f h w -> b (f h w) c")attention_mask = prepare_causal_attention_mask(- T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B)- hidden_states = attn(- hidden_states, temb=temb, attention_mask=attention_mask)- hidden_states = rearrange(- hidden_states, "b (f h w) c -> b c f h w", f=T, h=H, w=W)+ T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B+ )+ hidden_states = attn(hidden_states, temb=temb, attention_mask=attention_mask)+ hidden_states = rearrange(hidden_states, "b (f h w) c -> b c f h w", f=T, h=H, w=W)hidden_states = resnet(hidden_states, temb)return hidden_states