text
stringlengths
1
1.02k
class_index
int64
0
1.38k
source
stringclasses
431 values
resnets = [] for i in range(num_layers): in_channel = in_channels if i == 0 else out_channels resnets.append( CogVideoXResnetBlock3D( in_channels=in_channel, out_channels=out_channels, dropout=dropout, temb_channels=temb_channels, groups=resnet_groups, eps=resnet_eps, non_linearity=resnet_act_fn, pad_mode=pad_mode, ) ) self.resnets = nn.ModuleList(resnets) self.downsamplers = None if add_downsample: self.downsamplers = nn.ModuleList( [ CogVideoXDownsample3D( out_channels, out_channels, padding=downsample_padding, compress_time=compress_time ) ] ) self.gradient_checkpointing = False
1,174
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def forward( self, hidden_states: torch.Tensor, temb: Optional[torch.Tensor] = None, zq: Optional[torch.Tensor] = None, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: r"""Forward method of the `CogVideoXDownBlock3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {} for i, resnet in enumerate(self.resnets): conv_cache_key = f"resnet_{i}" if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward
1,174
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, temb, zq, conv_cache.get(conv_cache_key), ) else: hidden_states, new_conv_cache[conv_cache_key] = resnet( hidden_states, temb, zq, conv_cache=conv_cache.get(conv_cache_key) ) if self.downsamplers is not None: for downsampler in self.downsamplers: hidden_states = downsampler(hidden_states) return hidden_states, new_conv_cache
1,174
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
class CogVideoXMidBlock3D(nn.Module): r""" A middle block used in the CogVideoX model. Args: in_channels (`int`): Number of input channels. temb_channels (`int`, defaults to `512`): Number of time embedding channels. dropout (`float`, defaults to `0.0`): Dropout rate. num_layers (`int`, defaults to `1`): Number of resnet layers. resnet_eps (`float`, defaults to `1e-6`): Epsilon value for normalization layers. resnet_act_fn (`str`, defaults to `"swish"`): Activation function to use. resnet_groups (`int`, defaults to `32`): Number of groups to separate the channels into for group normalization. spatial_norm_dim (`int`, *optional*): The dimension to use for spatial norm if it is to be used instead of group norm. pad_mode (str, defaults to `"first"`): Padding mode. """ _supports_gradient_checkpointing = True
1,175
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def __init__( self, in_channels: int, temb_channels: int, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_act_fn: str = "swish", resnet_groups: int = 32, spatial_norm_dim: Optional[int] = None, pad_mode: str = "first", ): super().__init__() resnets = [] for _ in range(num_layers): resnets.append( CogVideoXResnetBlock3D( in_channels=in_channels, out_channels=in_channels, dropout=dropout, temb_channels=temb_channels, groups=resnet_groups, eps=resnet_eps, spatial_norm_dim=spatial_norm_dim, non_linearity=resnet_act_fn, pad_mode=pad_mode, ) ) self.resnets = nn.ModuleList(resnets) self.gradient_checkpointing = False
1,175
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def forward( self, hidden_states: torch.Tensor, temb: Optional[torch.Tensor] = None, zq: Optional[torch.Tensor] = None, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: r"""Forward method of the `CogVideoXMidBlock3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {} for i, resnet in enumerate(self.resnets): conv_cache_key = f"resnet_{i}" if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward
1,175
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, temb, zq, conv_cache.get(conv_cache_key) ) else: hidden_states, new_conv_cache[conv_cache_key] = resnet( hidden_states, temb, zq, conv_cache=conv_cache.get(conv_cache_key) ) return hidden_states, new_conv_cache
1,175
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
class CogVideoXUpBlock3D(nn.Module): r""" An upsampling block used in the CogVideoX model.
1,176
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Args: in_channels (`int`): Number of input channels. out_channels (`int`, *optional*): Number of output channels. If None, defaults to `in_channels`. temb_channels (`int`, defaults to `512`): Number of time embedding channels. dropout (`float`, defaults to `0.0`): Dropout rate. num_layers (`int`, defaults to `1`): Number of resnet layers. resnet_eps (`float`, defaults to `1e-6`): Epsilon value for normalization layers. resnet_act_fn (`str`, defaults to `"swish"`): Activation function to use. resnet_groups (`int`, defaults to `32`): Number of groups to separate the channels into for group normalization. spatial_norm_dim (`int`, defaults to `16`): The dimension to use for spatial norm if it is to be used instead of group norm. add_upsample (`bool`, defaults to `True`):
1,176
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Whether or not to use a upsampling layer. If not used, output dimension would be same as input dimension. compress_time (`bool`, defaults to `False`): Whether or not to downsample across temporal dimension. pad_mode (str, defaults to `"first"`): Padding mode. """
1,176
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def __init__( self, in_channels: int, out_channels: int, temb_channels: int, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_act_fn: str = "swish", resnet_groups: int = 32, spatial_norm_dim: int = 16, add_upsample: bool = True, upsample_padding: int = 1, compress_time: bool = False, pad_mode: str = "first", ): super().__init__()
1,176
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
resnets = [] for i in range(num_layers): in_channel = in_channels if i == 0 else out_channels resnets.append( CogVideoXResnetBlock3D( in_channels=in_channel, out_channels=out_channels, dropout=dropout, temb_channels=temb_channels, groups=resnet_groups, eps=resnet_eps, non_linearity=resnet_act_fn, spatial_norm_dim=spatial_norm_dim, pad_mode=pad_mode, ) ) self.resnets = nn.ModuleList(resnets) self.upsamplers = None if add_upsample: self.upsamplers = nn.ModuleList( [ CogVideoXUpsample3D( out_channels, out_channels, padding=upsample_padding, compress_time=compress_time ) ] )
1,176
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, temb: Optional[torch.Tensor] = None, zq: Optional[torch.Tensor] = None, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: r"""Forward method of the `CogVideoXUpBlock3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {} for i, resnet in enumerate(self.resnets): conv_cache_key = f"resnet_{i}" if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward
1,176
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, temb, zq, conv_cache.get(conv_cache_key), ) else: hidden_states, new_conv_cache[conv_cache_key] = resnet( hidden_states, temb, zq, conv_cache=conv_cache.get(conv_cache_key) ) if self.upsamplers is not None: for upsampler in self.upsamplers: hidden_states = upsampler(hidden_states) return hidden_states, new_conv_cache
1,176
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
class CogVideoXEncoder3D(nn.Module): r""" The `CogVideoXEncoder3D` layer of a variational autoencoder that encodes its input into a latent representation.
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Args: in_channels (`int`, *optional*, defaults to 3): The number of input channels. out_channels (`int`, *optional*, defaults to 3): The number of output channels. down_block_types (`Tuple[str, ...]`, *optional*, defaults to `("DownEncoderBlock2D",)`): The types of down blocks to use. See `~diffusers.models.unet_2d_blocks.get_down_block` for available options. block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`): The number of output channels for each block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. See `~diffusers.models.activations.get_activation` for available options. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups for normalization. """
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
_supports_gradient_checkpointing = True def __init__( self, in_channels: int = 3, out_channels: int = 16, down_block_types: Tuple[str, ...] = ( "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", ), block_out_channels: Tuple[int, ...] = (128, 256, 256, 512), layers_per_block: int = 3, act_fn: str = "silu", norm_eps: float = 1e-6, norm_num_groups: int = 32, dropout: float = 0.0, pad_mode: str = "first", temporal_compression_ratio: float = 4, ): super().__init__() # log2 of temporal_compress_times temporal_compress_level = int(np.log2(temporal_compression_ratio)) self.conv_in = CogVideoXCausalConv3d(in_channels, block_out_channels[0], kernel_size=3, pad_mode=pad_mode) self.down_blocks = nn.ModuleList([])
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# down blocks output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 compress_time = i < temporal_compress_level
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
if down_block_type == "CogVideoXDownBlock3D": down_block = CogVideoXDownBlock3D( in_channels=input_channel, out_channels=output_channel, temb_channels=0, dropout=dropout, num_layers=layers_per_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, add_downsample=not is_final_block, compress_time=compress_time, ) else: raise ValueError("Invalid `down_block_type` encountered. Must be `CogVideoXDownBlock3D`") self.down_blocks.append(down_block)
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# mid block self.mid_block = CogVideoXMidBlock3D( in_channels=block_out_channels[-1], temb_channels=0, dropout=dropout, num_layers=2, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, pad_mode=pad_mode, ) self.norm_out = nn.GroupNorm(norm_num_groups, block_out_channels[-1], eps=1e-6) self.conv_act = nn.SiLU() self.conv_out = CogVideoXCausalConv3d( block_out_channels[-1], 2 * out_channels, kernel_size=3, pad_mode=pad_mode ) self.gradient_checkpointing = False def forward( self, sample: torch.Tensor, temb: Optional[torch.Tensor] = None, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: r"""The forward method of the `CogVideoXEncoder3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {}
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
hidden_states, new_conv_cache["conv_in"] = self.conv_in(sample, conv_cache=conv_cache.get("conv_in")) if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs) return custom_forward # 1. Down for i, down_block in enumerate(self.down_blocks): conv_cache_key = f"down_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(down_block), hidden_states, temb, None, conv_cache.get(conv_cache_key), )
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# 2. Mid hidden_states, new_conv_cache["mid_block"] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block), hidden_states, temb, None, conv_cache.get("mid_block"), ) else: # 1. Down for i, down_block in enumerate(self.down_blocks): conv_cache_key = f"down_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = down_block( hidden_states, temb, None, conv_cache.get(conv_cache_key) ) # 2. Mid hidden_states, new_conv_cache["mid_block"] = self.mid_block( hidden_states, temb, None, conv_cache=conv_cache.get("mid_block") ) # 3. Post-process hidden_states = self.norm_out(hidden_states) hidden_states = self.conv_act(hidden_states)
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
hidden_states, new_conv_cache["conv_out"] = self.conv_out(hidden_states, conv_cache=conv_cache.get("conv_out")) return hidden_states, new_conv_cache
1,177
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
class CogVideoXDecoder3D(nn.Module): r""" The `CogVideoXDecoder3D` layer of a variational autoencoder that decodes its latent representation into an output sample.
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Args: in_channels (`int`, *optional*, defaults to 3): The number of input channels. out_channels (`int`, *optional*, defaults to 3): The number of output channels. up_block_types (`Tuple[str, ...]`, *optional*, defaults to `("UpDecoderBlock2D",)`): The types of up blocks to use. See `~diffusers.models.unet_2d_blocks.get_up_block` for available options. block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`): The number of output channels for each block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. See `~diffusers.models.activations.get_activation` for available options. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups for normalization. """ _supports_gradient_checkpointing = True
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def __init__( self, in_channels: int = 16, out_channels: int = 3, up_block_types: Tuple[str, ...] = ( "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", ), block_out_channels: Tuple[int, ...] = (128, 256, 256, 512), layers_per_block: int = 3, act_fn: str = "silu", norm_eps: float = 1e-6, norm_num_groups: int = 32, dropout: float = 0.0, pad_mode: str = "first", temporal_compression_ratio: float = 4, ): super().__init__() reversed_block_out_channels = list(reversed(block_out_channels)) self.conv_in = CogVideoXCausalConv3d( in_channels, reversed_block_out_channels[0], kernel_size=3, pad_mode=pad_mode )
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# mid block self.mid_block = CogVideoXMidBlock3D( in_channels=reversed_block_out_channels[0], temb_channels=0, num_layers=2, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, spatial_norm_dim=in_channels, pad_mode=pad_mode, ) # up blocks self.up_blocks = nn.ModuleList([]) output_channel = reversed_block_out_channels[0] temporal_compress_level = int(np.log2(temporal_compression_ratio)) for i, up_block_type in enumerate(up_block_types): prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 compress_time = i < temporal_compress_level
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
if up_block_type == "CogVideoXUpBlock3D": up_block = CogVideoXUpBlock3D( in_channels=prev_output_channel, out_channels=output_channel, temb_channels=0, dropout=dropout, num_layers=layers_per_block + 1, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, spatial_norm_dim=in_channels, add_upsample=not is_final_block, compress_time=compress_time, pad_mode=pad_mode, ) prev_output_channel = output_channel else: raise ValueError("Invalid `up_block_type` encountered. Must be `CogVideoXUpBlock3D`") self.up_blocks.append(up_block)
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
self.norm_out = CogVideoXSpatialNorm3D(reversed_block_out_channels[-1], in_channels, groups=norm_num_groups) self.conv_act = nn.SiLU() self.conv_out = CogVideoXCausalConv3d( reversed_block_out_channels[-1], out_channels, kernel_size=3, pad_mode=pad_mode ) self.gradient_checkpointing = False def forward( self, sample: torch.Tensor, temb: Optional[torch.Tensor] = None, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: r"""The forward method of the `CogVideoXDecoder3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {} hidden_states, new_conv_cache["conv_in"] = self.conv_in(sample, conv_cache=conv_cache.get("conv_in")) if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs)
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
return custom_forward # 1. Mid hidden_states, new_conv_cache["mid_block"] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block), hidden_states, temb, sample, conv_cache.get("mid_block"), ) # 2. Up for i, up_block in enumerate(self.up_blocks): conv_cache_key = f"up_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(up_block), hidden_states, temb, sample, conv_cache.get(conv_cache_key), ) else: # 1. Mid hidden_states, new_conv_cache["mid_block"] = self.mid_block( hidden_states, temb, sample, conv_cache=conv_cache.get("mid_block") )
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# 2. Up for i, up_block in enumerate(self.up_blocks): conv_cache_key = f"up_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = up_block( hidden_states, temb, sample, conv_cache=conv_cache.get(conv_cache_key) ) # 3. Post-process hidden_states, new_conv_cache["norm_out"] = self.norm_out( hidden_states, sample, conv_cache=conv_cache.get("norm_out") ) hidden_states = self.conv_act(hidden_states) hidden_states, new_conv_cache["conv_out"] = self.conv_out(hidden_states, conv_cache=conv_cache.get("conv_out")) return hidden_states, new_conv_cache
1,178
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
class AutoencoderKLCogVideoX(ModelMixin, ConfigMixin, FromOriginalModelMixin): r""" A VAE model with KL loss for encoding images into latents and decoding latent representations into images. Used in [CogVideoX](https://github.com/THUDM/CogVideo). This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented for all models (such as downloading or saving).
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Parameters: in_channels (int, *optional*, defaults to 3): Number of channels in the input image. out_channels (int, *optional*, defaults to 3): Number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`): Tuple of downsample block types. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`): Tuple of upsample block types. block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`): Tuple of block output channels. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. sample_size (`int`, *optional*, defaults to `32`): Sample input size. scaling_factor (`float`, *optional*, defaults to `1.15258426`): The component-wise standard deviation of the trained latent space computed using the first batch of the
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
training set. This is used to scale the latent space to have unit variance when training the diffusion model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper. force_upcast (`bool`, *optional*, default to `True`): If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE can be fine-tuned / trained to a lower range without loosing too much precision in which case `force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix """
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
_supports_gradient_checkpointing = True _no_split_modules = ["CogVideoXResnetBlock3D"]
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
@register_to_config def __init__( self, in_channels: int = 3, out_channels: int = 3, down_block_types: Tuple[str] = ( "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", ), up_block_types: Tuple[str] = ( "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", ), block_out_channels: Tuple[int] = (128, 256, 256, 512), latent_channels: int = 16, layers_per_block: int = 3, act_fn: str = "silu", norm_eps: float = 1e-6, norm_num_groups: int = 32, temporal_compression_ratio: float = 4, sample_height: int = 480, sample_width: int = 720, scaling_factor: float = 1.15258426, shift_factor: Optional[float] = None, latents_mean: Optional[Tuple[float]] = None,
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
latents_std: Optional[Tuple[float]] = None, force_upcast: float = True, use_quant_conv: bool = False, use_post_quant_conv: bool = False, invert_scale_latents: bool = False, ): super().__init__()
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
self.encoder = CogVideoXEncoder3D( in_channels=in_channels, out_channels=latent_channels, down_block_types=down_block_types, block_out_channels=block_out_channels, layers_per_block=layers_per_block, act_fn=act_fn, norm_eps=norm_eps, norm_num_groups=norm_num_groups, temporal_compression_ratio=temporal_compression_ratio, ) self.decoder = CogVideoXDecoder3D( in_channels=latent_channels, out_channels=out_channels, up_block_types=up_block_types, block_out_channels=block_out_channels, layers_per_block=layers_per_block, act_fn=act_fn, norm_eps=norm_eps, norm_num_groups=norm_num_groups, temporal_compression_ratio=temporal_compression_ratio, ) self.quant_conv = CogVideoXSafeConv3d(2 * out_channels, 2 * out_channels, 1) if use_quant_conv else None
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
self.post_quant_conv = CogVideoXSafeConv3d(out_channels, out_channels, 1) if use_post_quant_conv else None
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
self.use_slicing = False self.use_tiling = False
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# Can be increased to decode more latent frames at once, but comes at a reasonable memory cost and it is not # recommended because the temporal parts of the VAE, here, are tricky to understand. # If you decode X latent frames together, the number of output frames is: # (X + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) => X + 6 frames # # Example with num_latent_frames_batch_size = 2: # - 12 latent frames: (0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11) are processed together # => (12 // 2 frame slices) * ((2 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) # => 6 * 8 = 48 frames # - 13 latent frames: (0, 1, 2) (special case), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12) are processed together
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# => (1 frame slice) * ((3 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) + # ((13 - 3) // 2) * ((2 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) # => 1 * 9 + 5 * 8 = 49 frames # It has been implemented this way so as to not have "magic values" in the code base that would be hard to explain. Note that # setting it to anything other than 2 would give poor results because the VAE hasn't been trained to be adaptive with different # number of temporal frames. self.num_latent_frames_batch_size = 2 self.num_sample_frames_batch_size = 8
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# We make the minimum height and width of sample for tiling half that of the generally supported self.tile_sample_min_height = sample_height // 2 self.tile_sample_min_width = sample_width // 2 self.tile_latent_min_height = int( self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1)) ) self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1))) # These are experimental overlap factors that were chosen based on experimentation and seem to work best for # 720x480 (WxH) resolution. The above resolution is the strongly recommended generation resolution in CogVideoX # and so the tiling implementation has only been tested on those specific resolutions. self.tile_overlap_factor_height = 1 / 6 self.tile_overlap_factor_width = 1 / 5
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, (CogVideoXEncoder3D, CogVideoXDecoder3D)): module.gradient_checkpointing = value def enable_tiling( self, tile_sample_min_height: Optional[int] = None, tile_sample_min_width: Optional[int] = None, tile_overlap_factor_height: Optional[float] = None, tile_overlap_factor_width: Optional[float] = None, ) -> None: r""" Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow processing larger images.
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Args: tile_sample_min_height (`int`, *optional*): The minimum height required for a sample to be separated into tiles across the height dimension. tile_sample_min_width (`int`, *optional*): The minimum width required for a sample to be separated into tiles across the width dimension. tile_overlap_factor_height (`int`, *optional*): The minimum amount of overlap between two consecutive vertical tiles. This is to ensure that there are no tiling artifacts produced across the height dimension. Must be between 0 and 1. Setting a higher value might cause more tiles to be processed leading to slow down of the decoding process. tile_overlap_factor_width (`int`, *optional*): The minimum amount of overlap between two consecutive horizontal tiles. This is to ensure that there
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
are no tiling artifacts produced across the width dimension. Must be between 0 and 1. Setting a higher value might cause more tiles to be processed leading to slow down of the decoding process. """ self.use_tiling = True self.tile_sample_min_height = tile_sample_min_height or self.tile_sample_min_height self.tile_sample_min_width = tile_sample_min_width or self.tile_sample_min_width self.tile_latent_min_height = int( self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1)) ) self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1))) self.tile_overlap_factor_height = tile_overlap_factor_height or self.tile_overlap_factor_height self.tile_overlap_factor_width = tile_overlap_factor_width or self.tile_overlap_factor_width
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def disable_tiling(self) -> None: r""" Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing decoding in one step. """ self.use_tiling = False def enable_slicing(self) -> None: r""" Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several steps. This is useful to save some memory and allow larger batch sizes. """ self.use_slicing = True def disable_slicing(self) -> None: r""" Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing decoding in one step. """ self.use_slicing = False def _encode(self, x: torch.Tensor) -> torch.Tensor: batch_size, num_channels, num_frames, height, width = x.shape
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
if self.use_tiling and (width > self.tile_sample_min_width or height > self.tile_sample_min_height): return self.tiled_encode(x) frame_batch_size = self.num_sample_frames_batch_size # Note: We expect the number of frames to be either `1` or `frame_batch_size * k` or `frame_batch_size * k + 1` for some k. # As the extra single frame is handled inside the loop, it is not required to round up here. num_batches = max(num_frames // frame_batch_size, 1) conv_cache = None enc = []
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
for i in range(num_batches): remaining_frames = num_frames % frame_batch_size start_frame = frame_batch_size * i + (0 if i == 0 else remaining_frames) end_frame = frame_batch_size * (i + 1) + remaining_frames x_intermediate = x[:, :, start_frame:end_frame] x_intermediate, conv_cache = self.encoder(x_intermediate, conv_cache=conv_cache) if self.quant_conv is not None: x_intermediate = self.quant_conv(x_intermediate) enc.append(x_intermediate) enc = torch.cat(enc, dim=2) return enc @apply_forward_hook def encode( self, x: torch.Tensor, return_dict: bool = True ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]: """ Encode a batch of images into latents.
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Args: x (`torch.Tensor`): Input batch of images. return_dict (`bool`, *optional*, defaults to `True`): Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple. Returns: The latent representations of the encoded videos. If `return_dict` is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned. """ if self.use_slicing and x.shape[0] > 1: encoded_slices = [self._encode(x_slice) for x_slice in x.split(1)] h = torch.cat(encoded_slices) else: h = self._encode(x) posterior = DiagonalGaussianDistribution(h) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=posterior)
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def _decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]: batch_size, num_channels, num_frames, height, width = z.shape if self.use_tiling and (width > self.tile_latent_min_width or height > self.tile_latent_min_height): return self.tiled_decode(z, return_dict=return_dict) frame_batch_size = self.num_latent_frames_batch_size num_batches = max(num_frames // frame_batch_size, 1) conv_cache = None dec = []
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
for i in range(num_batches): remaining_frames = num_frames % frame_batch_size start_frame = frame_batch_size * i + (0 if i == 0 else remaining_frames) end_frame = frame_batch_size * (i + 1) + remaining_frames z_intermediate = z[:, :, start_frame:end_frame] if self.post_quant_conv is not None: z_intermediate = self.post_quant_conv(z_intermediate) z_intermediate, conv_cache = self.decoder(z_intermediate, conv_cache=conv_cache) dec.append(z_intermediate) dec = torch.cat(dec, dim=2) if not return_dict: return (dec,) return DecoderOutput(sample=dec) @apply_forward_hook def decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]: """ Decode a batch of images.
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Args: z (`torch.Tensor`): Input batch of latent vectors. return_dict (`bool`, *optional*, defaults to `True`): Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple. Returns: [`~models.vae.DecoderOutput`] or `tuple`: If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is returned. """ if self.use_slicing and z.shape[0] > 1: decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)] decoded = torch.cat(decoded_slices) else: decoded = self._decode(z).sample if not return_dict: return (decoded,) return DecoderOutput(sample=decoded)
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[3], b.shape[3], blend_extent) for y in range(blend_extent): b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * ( y / blend_extent ) return b def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[4], b.shape[4], blend_extent) for x in range(blend_extent): b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * ( x / blend_extent ) return b def tiled_encode(self, x: torch.Tensor) -> torch.Tensor: r"""Encode a batch of images using a tiled encoder.
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the output, but they should be much less noticeable. Args: x (`torch.Tensor`): Input batch of videos. Returns: `torch.Tensor`: The latent representation of the encoded videos. """ # For a rough memory estimate, take a look at the `tiled_decode` method. batch_size, num_channels, num_frames, height, width = x.shape
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
overlap_height = int(self.tile_sample_min_height * (1 - self.tile_overlap_factor_height)) overlap_width = int(self.tile_sample_min_width * (1 - self.tile_overlap_factor_width)) blend_extent_height = int(self.tile_latent_min_height * self.tile_overlap_factor_height) blend_extent_width = int(self.tile_latent_min_width * self.tile_overlap_factor_width) row_limit_height = self.tile_latent_min_height - blend_extent_height row_limit_width = self.tile_latent_min_width - blend_extent_width frame_batch_size = self.num_sample_frames_batch_size
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# Split x into overlapping tiles and encode them separately. # The tiles have an overlap to avoid seams between tiles. rows = [] for i in range(0, height, overlap_height): row = [] for j in range(0, width, overlap_width): # Note: We expect the number of frames to be either `1` or `frame_batch_size * k` or `frame_batch_size * k + 1` for some k. # As the extra single frame is handled inside the loop, it is not required to round up here. num_batches = max(num_frames // frame_batch_size, 1) conv_cache = None time = []
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
for k in range(num_batches): remaining_frames = num_frames % frame_batch_size start_frame = frame_batch_size * k + (0 if k == 0 else remaining_frames) end_frame = frame_batch_size * (k + 1) + remaining_frames tile = x[ :, :, start_frame:end_frame, i : i + self.tile_sample_min_height, j : j + self.tile_sample_min_width, ] tile, conv_cache = self.encoder(tile, conv_cache=conv_cache) if self.quant_conv is not None: tile = self.quant_conv(tile) time.append(tile) row.append(torch.cat(time, dim=2)) rows.append(row)
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent_height) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent_width) result_row.append(tile[:, :, :, :row_limit_height, :row_limit_width]) result_rows.append(torch.cat(result_row, dim=4)) enc = torch.cat(result_rows, dim=3) return enc def tiled_decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]: r""" Decode a batch of images using a tiled decoder.
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
Args: z (`torch.Tensor`): Input batch of latent vectors. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple. Returns: [`~models.vae.DecoderOutput`] or `tuple`: If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is returned. """ # Rough memory assessment: # - In CogVideoX-2B, there are a total of 24 CausalConv3d layers. # - The biggest intermediate dimensions are: [1, 128, 9, 480, 720]. # - Assume fp16 (2 bytes per value). # Memory required: 1 * 128 * 9 * 480 * 720 * 24 * 2 / 1024**3 = 17.8 GB # # Memory assessment when using tiling: # - Assume everything as above but now HxW is 240x360 by tiling in half # Memory required: 1 * 128 * 9 * 240 * 360 * 24 * 2 / 1024**3 = 4.5 GB
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
batch_size, num_channels, num_frames, height, width = z.shape overlap_height = int(self.tile_latent_min_height * (1 - self.tile_overlap_factor_height)) overlap_width = int(self.tile_latent_min_width * (1 - self.tile_overlap_factor_width)) blend_extent_height = int(self.tile_sample_min_height * self.tile_overlap_factor_height) blend_extent_width = int(self.tile_sample_min_width * self.tile_overlap_factor_width) row_limit_height = self.tile_sample_min_height - blend_extent_height row_limit_width = self.tile_sample_min_width - blend_extent_width frame_batch_size = self.num_latent_frames_batch_size
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
# Split z into overlapping tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. rows = [] for i in range(0, height, overlap_height): row = [] for j in range(0, width, overlap_width): num_batches = max(num_frames // frame_batch_size, 1) conv_cache = None time = []
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
for k in range(num_batches): remaining_frames = num_frames % frame_batch_size start_frame = frame_batch_size * k + (0 if k == 0 else remaining_frames) end_frame = frame_batch_size * (k + 1) + remaining_frames tile = z[ :, :, start_frame:end_frame, i : i + self.tile_latent_min_height, j : j + self.tile_latent_min_width, ] if self.post_quant_conv is not None: tile = self.post_quant_conv(tile) tile, conv_cache = self.decoder(tile, conv_cache=conv_cache) time.append(tile) row.append(torch.cat(time, dim=2)) rows.append(row)
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent_height) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent_width) result_row.append(tile[:, :, :, :row_limit_height, :row_limit_width]) result_rows.append(torch.cat(result_row, dim=4)) dec = torch.cat(result_rows, dim=3) if not return_dict: return (dec,) return DecoderOutput(sample=dec)
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
def forward( self, sample: torch.Tensor, sample_posterior: bool = False, return_dict: bool = True, generator: Optional[torch.Generator] = None, ) -> Union[torch.Tensor, torch.Tensor]: x = sample posterior = self.encode(x).latent_dist if sample_posterior: z = posterior.sample(generator=generator) else: z = posterior.mode() dec = self.decode(z).sample if not return_dict: return (dec,) return DecoderOutput(sample=dec)
1,179
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py
class MochiChunkedGroupNorm3D(nn.Module): r""" Applies per-frame group normalization for 5D video inputs. It also supports memory-efficient chunked group normalization. Args: num_channels (int): Number of channels expected in input num_groups (int, optional): Number of groups to separate the channels into. Default: 32 affine (bool, optional): If True, this module has learnable affine parameters. Default: True chunk_size (int, optional): Size of each chunk for processing. Default: 8 """ def __init__( self, num_channels: int, num_groups: int = 32, affine: bool = True, chunk_size: int = 8, ): super().__init__() self.norm_layer = nn.GroupNorm(num_channels=num_channels, num_groups=num_groups, affine=affine) self.chunk_size = chunk_size def forward(self, x: torch.Tensor = None) -> torch.Tensor: batch_size = x.size(0)
1,180
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
x = x.permute(0, 2, 1, 3, 4).flatten(0, 1) output = torch.cat([self.norm_layer(chunk) for chunk in x.split(self.chunk_size, dim=0)], dim=0) output = output.unflatten(0, (batch_size, -1)).permute(0, 2, 1, 3, 4) return output
1,180
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
class MochiResnetBlock3D(nn.Module): r""" A 3D ResNet block used in the Mochi model. Args: in_channels (`int`): Number of input channels. out_channels (`int`, *optional*): Number of output channels. If None, defaults to `in_channels`. non_linearity (`str`, defaults to `"swish"`): Activation function to use. """ def __init__( self, in_channels: int, out_channels: Optional[int] = None, act_fn: str = "swish", ): super().__init__() out_channels = out_channels or in_channels self.in_channels = in_channels self.out_channels = out_channels self.nonlinearity = get_activation(act_fn)
1,181
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
self.norm1 = MochiChunkedGroupNorm3D(num_channels=in_channels) self.conv1 = CogVideoXCausalConv3d( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, pad_mode="replicate" ) self.norm2 = MochiChunkedGroupNorm3D(num_channels=out_channels) self.conv2 = CogVideoXCausalConv3d( in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, pad_mode="replicate" ) def forward( self, inputs: torch.Tensor, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: new_conv_cache = {} conv_cache = conv_cache or {} hidden_states = inputs hidden_states = self.norm1(hidden_states) hidden_states = self.nonlinearity(hidden_states) hidden_states, new_conv_cache["conv1"] = self.conv1(hidden_states, conv_cache=conv_cache.get("conv1"))
1,181
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
hidden_states = self.norm2(hidden_states) hidden_states = self.nonlinearity(hidden_states) hidden_states, new_conv_cache["conv2"] = self.conv2(hidden_states, conv_cache=conv_cache.get("conv2")) hidden_states = hidden_states + inputs return hidden_states, new_conv_cache
1,181
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
class MochiDownBlock3D(nn.Module): r""" An downsampling block used in the Mochi model. Args: in_channels (`int`): Number of input channels. out_channels (`int`, *optional*): Number of output channels. If None, defaults to `in_channels`. num_layers (`int`, defaults to `1`): Number of resnet blocks in the block. temporal_expansion (`int`, defaults to `2`): Temporal expansion factor. spatial_expansion (`int`, defaults to `2`): Spatial expansion factor. """ def __init__( self, in_channels: int, out_channels: int, num_layers: int = 1, temporal_expansion: int = 2, spatial_expansion: int = 2, add_attention: bool = True, ): super().__init__() self.temporal_expansion = temporal_expansion self.spatial_expansion = spatial_expansion
1,182
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
self.conv_in = CogVideoXCausalConv3d( in_channels=in_channels, out_channels=out_channels, kernel_size=(temporal_expansion, spatial_expansion, spatial_expansion), stride=(temporal_expansion, spatial_expansion, spatial_expansion), pad_mode="replicate", )
1,182
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
resnets = [] norms = [] attentions = [] for _ in range(num_layers): resnets.append(MochiResnetBlock3D(in_channels=out_channels)) if add_attention: norms.append(MochiChunkedGroupNorm3D(num_channels=out_channels)) attentions.append( Attention( query_dim=out_channels, heads=out_channels // 32, dim_head=32, qk_norm="l2", is_causal=True, processor=MochiVaeAttnProcessor2_0(), ) ) else: norms.append(None) attentions.append(None) self.resnets = nn.ModuleList(resnets) self.norms = nn.ModuleList(norms) self.attentions = nn.ModuleList(attentions) self.gradient_checkpointing = False
1,182
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
def forward( self, hidden_states: torch.Tensor, conv_cache: Optional[Dict[str, torch.Tensor]] = None, chunk_size: int = 2**15, ) -> torch.Tensor: r"""Forward method of the `MochiUpBlock3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {} hidden_states, new_conv_cache["conv_in"] = self.conv_in(hidden_states) for i, (resnet, norm, attn) in enumerate(zip(self.resnets, self.norms, self.attentions)): conv_cache_key = f"resnet_{i}" if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward
1,182
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, conv_cache=conv_cache.get(conv_cache_key), ) else: hidden_states, new_conv_cache[conv_cache_key] = resnet( hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) if attn is not None: residual = hidden_states hidden_states = norm(hidden_states) batch_size, num_channels, num_frames, height, width = hidden_states.shape hidden_states = hidden_states.permute(0, 3, 4, 2, 1).flatten(0, 2).contiguous()
1,182
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
# Perform attention in chunks to avoid following error: # RuntimeError: CUDA error: invalid configuration argument if hidden_states.size(0) <= chunk_size: hidden_states = attn(hidden_states) else: hidden_states_chunks = [] for i in range(0, hidden_states.size(0), chunk_size): hidden_states_chunk = hidden_states[i : i + chunk_size] hidden_states_chunk = attn(hidden_states_chunk) hidden_states_chunks.append(hidden_states_chunk) hidden_states = torch.cat(hidden_states_chunks) hidden_states = hidden_states.unflatten(0, (batch_size, height, width)).permute(0, 4, 3, 1, 2) hidden_states = residual + hidden_states return hidden_states, new_conv_cache
1,182
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
class MochiMidBlock3D(nn.Module): r""" A middle block used in the Mochi model. Args: in_channels (`int`): Number of input channels. num_layers (`int`, defaults to `3`): Number of resnet blocks in the block. """ def __init__( self, in_channels: int, # 768 num_layers: int = 3, add_attention: bool = True, ): super().__init__() resnets = [] norms = [] attentions = [] for _ in range(num_layers): resnets.append(MochiResnetBlock3D(in_channels=in_channels))
1,183
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
if add_attention: norms.append(MochiChunkedGroupNorm3D(num_channels=in_channels)) attentions.append( Attention( query_dim=in_channels, heads=in_channels // 32, dim_head=32, qk_norm="l2", is_causal=True, processor=MochiVaeAttnProcessor2_0(), ) ) else: norms.append(None) attentions.append(None) self.resnets = nn.ModuleList(resnets) self.norms = nn.ModuleList(norms) self.attentions = nn.ModuleList(attentions) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: r"""Forward method of the `MochiMidBlock3D` class."""
1,183
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
new_conv_cache = {} conv_cache = conv_cache or {} for i, (resnet, norm, attn) in enumerate(zip(self.resnets, self.norms, self.attentions)): conv_cache_key = f"resnet_{i}" if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) else: hidden_states, new_conv_cache[conv_cache_key] = resnet( hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) if attn is not None: residual = hidden_states hidden_states = norm(hidden_states)
1,183
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
batch_size, num_channels, num_frames, height, width = hidden_states.shape hidden_states = hidden_states.permute(0, 3, 4, 2, 1).flatten(0, 2).contiguous() hidden_states = attn(hidden_states) hidden_states = hidden_states.unflatten(0, (batch_size, height, width)).permute(0, 4, 3, 1, 2) hidden_states = residual + hidden_states return hidden_states, new_conv_cache
1,183
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
class MochiUpBlock3D(nn.Module): r""" An upsampling block used in the Mochi model. Args: in_channels (`int`): Number of input channels. out_channels (`int`, *optional*): Number of output channels. If None, defaults to `in_channels`. num_layers (`int`, defaults to `1`): Number of resnet blocks in the block. temporal_expansion (`int`, defaults to `2`): Temporal expansion factor. spatial_expansion (`int`, defaults to `2`): Spatial expansion factor. """ def __init__( self, in_channels: int, out_channels: int, num_layers: int = 1, temporal_expansion: int = 2, spatial_expansion: int = 2, ): super().__init__() self.temporal_expansion = temporal_expansion self.spatial_expansion = spatial_expansion
1,184
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
resnets = [] for _ in range(num_layers): resnets.append(MochiResnetBlock3D(in_channels=in_channels)) self.resnets = nn.ModuleList(resnets) self.proj = nn.Linear(in_channels, out_channels * temporal_expansion * spatial_expansion**2) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, conv_cache: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.Tensor: r"""Forward method of the `MochiUpBlock3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {} for i, resnet in enumerate(self.resnets): conv_cache_key = f"resnet_{i}" if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward
1,184
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, conv_cache=conv_cache.get(conv_cache_key), ) else: hidden_states, new_conv_cache[conv_cache_key] = resnet( hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) hidden_states = hidden_states.permute(0, 2, 3, 4, 1) hidden_states = self.proj(hidden_states) hidden_states = hidden_states.permute(0, 4, 1, 2, 3) batch_size, num_channels, num_frames, height, width = hidden_states.shape st = self.temporal_expansion sh = self.spatial_expansion sw = self.spatial_expansion
1,184
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
# Reshape and unpatchify hidden_states = hidden_states.view(batch_size, -1, st, sh, sw, num_frames, height, width) hidden_states = hidden_states.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous() hidden_states = hidden_states.view(batch_size, -1, num_frames * st, height * sh, width * sw) return hidden_states, new_conv_cache
1,184
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
class FourierFeatures(nn.Module): def __init__(self, start: int = 6, stop: int = 8, step: int = 1): super().__init__() self.start = start self.stop = stop self.step = step def forward(self, inputs: torch.Tensor) -> torch.Tensor: r"""Forward method of the `FourierFeatures` class.""" original_dtype = inputs.dtype inputs = inputs.to(torch.float32) num_channels = inputs.shape[1] num_freqs = (self.stop - self.start) // self.step freqs = torch.arange(self.start, self.stop, self.step, dtype=inputs.dtype, device=inputs.device) w = torch.pow(2.0, freqs) * (2 * torch.pi) # [num_freqs] w = w.repeat(num_channels)[None, :, None, None, None] # [1, num_channels * num_freqs, 1, 1, 1] # Interleaved repeat of input channels to match w h = inputs.repeat_interleave(num_freqs, dim=1) # [B, C * num_freqs, T, H, W] # Scale channels by frequency. h = w * h
1,185
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
return torch.cat([inputs, torch.sin(h), torch.cos(h)], dim=1).to(original_dtype)
1,185
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
class MochiEncoder3D(nn.Module): r""" The `MochiEncoder3D` layer of a variational autoencoder that encodes input video samples to its latent representation.
1,186
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
Args: in_channels (`int`, *optional*): The number of input channels. out_channels (`int`, *optional*): The number of output channels. block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(128, 256, 512, 768)`): The number of output channels for each block. layers_per_block (`Tuple[int, ...]`, *optional*, defaults to `(3, 3, 4, 6, 3)`): The number of resnet blocks for each block. temporal_expansions (`Tuple[int, ...]`, *optional*, defaults to `(1, 2, 3)`): The temporal expansion factor for each of the up blocks. spatial_expansions (`Tuple[int, ...]`, *optional*, defaults to `(2, 2, 2)`): The spatial expansion factor for each of the up blocks. non_linearity (`str`, *optional*, defaults to `"swish"`): The non-linearity to use in the decoder. """
1,186
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
def __init__( self, in_channels: int, out_channels: int, block_out_channels: Tuple[int, ...] = (128, 256, 512, 768), layers_per_block: Tuple[int, ...] = (3, 3, 4, 6, 3), temporal_expansions: Tuple[int, ...] = (1, 2, 3), spatial_expansions: Tuple[int, ...] = (2, 2, 2), add_attention_block: Tuple[bool, ...] = (False, True, True, True, True), act_fn: str = "swish", ): super().__init__() self.nonlinearity = get_activation(act_fn) self.fourier_features = FourierFeatures() self.proj_in = nn.Linear(in_channels, block_out_channels[0]) self.block_in = MochiMidBlock3D( in_channels=block_out_channels[0], num_layers=layers_per_block[0], add_attention=add_attention_block[0] )
1,186
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
down_blocks = [] for i in range(len(block_out_channels) - 1): down_block = MochiDownBlock3D( in_channels=block_out_channels[i], out_channels=block_out_channels[i + 1], num_layers=layers_per_block[i + 1], temporal_expansion=temporal_expansions[i], spatial_expansion=spatial_expansions[i], add_attention=add_attention_block[i + 1], ) down_blocks.append(down_block) self.down_blocks = nn.ModuleList(down_blocks) self.block_out = MochiMidBlock3D( in_channels=block_out_channels[-1], num_layers=layers_per_block[-1], add_attention=add_attention_block[-1] ) self.norm_out = MochiChunkedGroupNorm3D(block_out_channels[-1]) self.proj_out = nn.Linear(block_out_channels[-1], 2 * out_channels, bias=False)
1,186
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
def forward( self, hidden_states: torch.Tensor, conv_cache: Optional[Dict[str, torch.Tensor]] = None ) -> torch.Tensor: r"""Forward method of the `MochiEncoder3D` class.""" new_conv_cache = {} conv_cache = conv_cache or {} hidden_states = self.fourier_features(hidden_states) hidden_states = hidden_states.permute(0, 2, 3, 4, 1) hidden_states = self.proj_in(hidden_states) hidden_states = hidden_states.permute(0, 4, 1, 2, 3) if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward hidden_states, new_conv_cache["block_in"] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.block_in), hidden_states, conv_cache=conv_cache.get("block_in") )
1,186
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
for i, down_block in enumerate(self.down_blocks): conv_cache_key = f"down_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(down_block), hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) else: hidden_states, new_conv_cache["block_in"] = self.block_in( hidden_states, conv_cache=conv_cache.get("block_in") ) for i, down_block in enumerate(self.down_blocks): conv_cache_key = f"down_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = down_block( hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) hidden_states, new_conv_cache["block_out"] = self.block_out( hidden_states, conv_cache=conv_cache.get("block_out") )
1,186
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
hidden_states = self.norm_out(hidden_states) hidden_states = self.nonlinearity(hidden_states) hidden_states = hidden_states.permute(0, 2, 3, 4, 1) hidden_states = self.proj_out(hidden_states) hidden_states = hidden_states.permute(0, 4, 1, 2, 3) return hidden_states, new_conv_cache
1,186
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
class MochiDecoder3D(nn.Module): r""" The `MochiDecoder3D` layer of a variational autoencoder that decodes its latent representation into an output sample.
1,187
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
Args: in_channels (`int`, *optional*): The number of input channels. out_channels (`int`, *optional*): The number of output channels. block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(128, 256, 512, 768)`): The number of output channels for each block. layers_per_block (`Tuple[int, ...]`, *optional*, defaults to `(3, 3, 4, 6, 3)`): The number of resnet blocks for each block. temporal_expansions (`Tuple[int, ...]`, *optional*, defaults to `(1, 2, 3)`): The temporal expansion factor for each of the up blocks. spatial_expansions (`Tuple[int, ...]`, *optional*, defaults to `(2, 2, 2)`): The spatial expansion factor for each of the up blocks. non_linearity (`str`, *optional*, defaults to `"swish"`): The non-linearity to use in the decoder. """
1,187
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
def __init__( self, in_channels: int, # 12 out_channels: int, # 3 block_out_channels: Tuple[int, ...] = (128, 256, 512, 768), layers_per_block: Tuple[int, ...] = (3, 3, 4, 6, 3), temporal_expansions: Tuple[int, ...] = (1, 2, 3), spatial_expansions: Tuple[int, ...] = (2, 2, 2), act_fn: str = "swish", ): super().__init__() self.nonlinearity = get_activation(act_fn) self.conv_in = nn.Conv3d(in_channels, block_out_channels[-1], kernel_size=(1, 1, 1)) self.block_in = MochiMidBlock3D( in_channels=block_out_channels[-1], num_layers=layers_per_block[-1], add_attention=False, )
1,187
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
up_blocks = [] for i in range(len(block_out_channels) - 1): up_block = MochiUpBlock3D( in_channels=block_out_channels[-i - 1], out_channels=block_out_channels[-i - 2], num_layers=layers_per_block[-i - 2], temporal_expansion=temporal_expansions[-i - 1], spatial_expansion=spatial_expansions[-i - 1], ) up_blocks.append(up_block) self.up_blocks = nn.ModuleList(up_blocks) self.block_out = MochiMidBlock3D( in_channels=block_out_channels[0], num_layers=layers_per_block[0], add_attention=False, ) self.proj_out = nn.Linear(block_out_channels[0], out_channels) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, conv_cache: Optional[Dict[str, torch.Tensor]] = None ) -> torch.Tensor: r"""Forward method of the `MochiDecoder3D` class."""
1,187
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
new_conv_cache = {} conv_cache = conv_cache or {} hidden_states = self.conv_in(hidden_states) # 1. Mid if torch.is_grad_enabled() and self.gradient_checkpointing: def create_custom_forward(module): def create_forward(*inputs): return module(*inputs) return create_forward hidden_states, new_conv_cache["block_in"] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.block_in), hidden_states, conv_cache=conv_cache.get("block_in") )
1,187
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
for i, up_block in enumerate(self.up_blocks): conv_cache_key = f"up_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint( create_custom_forward(up_block), hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) else: hidden_states, new_conv_cache["block_in"] = self.block_in( hidden_states, conv_cache=conv_cache.get("block_in") ) for i, up_block in enumerate(self.up_blocks): conv_cache_key = f"up_block_{i}" hidden_states, new_conv_cache[conv_cache_key] = up_block( hidden_states, conv_cache=conv_cache.get(conv_cache_key) ) hidden_states, new_conv_cache["block_out"] = self.block_out( hidden_states, conv_cache=conv_cache.get("block_out") ) hidden_states = self.nonlinearity(hidden_states)
1,187
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py
hidden_states = hidden_states.permute(0, 2, 3, 4, 1) hidden_states = self.proj_out(hidden_states) hidden_states = hidden_states.permute(0, 4, 1, 2, 3) return hidden_states, new_conv_cache
1,187
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/autoencoders/autoencoder_kl_mochi.py