diffusers 0.29.2__py3-none-any.whl → 0.30.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. diffusers/__init__.py +94 -3
  2. diffusers/commands/env.py +1 -5
  3. diffusers/configuration_utils.py +4 -9
  4. diffusers/dependency_versions_table.py +2 -2
  5. diffusers/image_processor.py +1 -2
  6. diffusers/loaders/__init__.py +17 -2
  7. diffusers/loaders/ip_adapter.py +10 -7
  8. diffusers/loaders/lora_base.py +752 -0
  9. diffusers/loaders/lora_pipeline.py +2252 -0
  10. diffusers/loaders/peft.py +213 -5
  11. diffusers/loaders/single_file.py +3 -14
  12. diffusers/loaders/single_file_model.py +31 -10
  13. diffusers/loaders/single_file_utils.py +293 -8
  14. diffusers/loaders/textual_inversion.py +1 -6
  15. diffusers/loaders/unet.py +23 -208
  16. diffusers/models/__init__.py +20 -0
  17. diffusers/models/activations.py +22 -0
  18. diffusers/models/attention.py +386 -7
  19. diffusers/models/attention_processor.py +1937 -629
  20. diffusers/models/autoencoders/__init__.py +2 -0
  21. diffusers/models/autoencoders/autoencoder_kl.py +14 -3
  22. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1271 -0
  23. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
  24. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  25. diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
  26. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  27. diffusers/models/autoencoders/vq_model.py +4 -4
  28. diffusers/models/controlnet.py +2 -3
  29. diffusers/models/controlnet_hunyuan.py +401 -0
  30. diffusers/models/controlnet_sd3.py +11 -11
  31. diffusers/models/controlnet_sparsectrl.py +789 -0
  32. diffusers/models/controlnet_xs.py +40 -10
  33. diffusers/models/downsampling.py +68 -0
  34. diffusers/models/embeddings.py +403 -36
  35. diffusers/models/model_loading_utils.py +1 -3
  36. diffusers/models/modeling_flax_utils.py +1 -6
  37. diffusers/models/modeling_utils.py +4 -16
  38. diffusers/models/normalization.py +203 -12
  39. diffusers/models/transformers/__init__.py +6 -0
  40. diffusers/models/transformers/auraflow_transformer_2d.py +543 -0
  41. diffusers/models/transformers/cogvideox_transformer_3d.py +485 -0
  42. diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
  43. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  44. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  45. diffusers/models/transformers/pixart_transformer_2d.py +102 -1
  46. diffusers/models/transformers/prior_transformer.py +1 -1
  47. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  48. diffusers/models/transformers/transformer_flux.py +455 -0
  49. diffusers/models/transformers/transformer_sd3.py +18 -4
  50. diffusers/models/unets/unet_1d_blocks.py +1 -1
  51. diffusers/models/unets/unet_2d_condition.py +8 -1
  52. diffusers/models/unets/unet_3d_blocks.py +51 -920
  53. diffusers/models/unets/unet_3d_condition.py +4 -1
  54. diffusers/models/unets/unet_i2vgen_xl.py +4 -1
  55. diffusers/models/unets/unet_kandinsky3.py +1 -1
  56. diffusers/models/unets/unet_motion_model.py +1330 -84
  57. diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
  58. diffusers/models/unets/unet_stable_cascade.py +1 -3
  59. diffusers/models/unets/uvit_2d.py +1 -1
  60. diffusers/models/upsampling.py +64 -0
  61. diffusers/models/vq_model.py +8 -4
  62. diffusers/optimization.py +1 -1
  63. diffusers/pipelines/__init__.py +100 -3
  64. diffusers/pipelines/animatediff/__init__.py +4 -0
  65. diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
  66. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
  67. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
  68. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
  69. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
  70. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  71. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
  72. diffusers/pipelines/aura_flow/__init__.py +48 -0
  73. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
  74. diffusers/pipelines/auto_pipeline.py +97 -19
  75. diffusers/pipelines/cogvideo/__init__.py +48 -0
  76. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +746 -0
  77. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  78. diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
  79. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
  80. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
  81. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
  82. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
  83. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
  84. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  85. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  86. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
  87. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
  88. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
  89. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
  90. diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
  91. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
  92. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
  93. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
  94. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
  95. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
  96. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
  97. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
  98. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  100. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
  101. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
  102. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
  103. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  104. diffusers/pipelines/flux/__init__.py +47 -0
  105. diffusers/pipelines/flux/pipeline_flux.py +749 -0
  106. diffusers/pipelines/flux/pipeline_output.py +21 -0
  107. diffusers/pipelines/free_init_utils.py +2 -0
  108. diffusers/pipelines/free_noise_utils.py +236 -0
  109. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
  110. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
  111. diffusers/pipelines/kolors/__init__.py +54 -0
  112. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  113. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
  114. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  115. diffusers/pipelines/kolors/text_encoder.py +889 -0
  116. diffusers/pipelines/kolors/tokenizer.py +334 -0
  117. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
  118. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
  119. diffusers/pipelines/latte/__init__.py +48 -0
  120. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  121. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
  122. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
  123. diffusers/pipelines/lumina/__init__.py +48 -0
  124. diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
  125. diffusers/pipelines/pag/__init__.py +67 -0
  126. diffusers/pipelines/pag/pag_utils.py +237 -0
  127. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
  128. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
  129. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
  130. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  131. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
  132. diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
  133. diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
  134. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
  135. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
  136. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
  137. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
  138. diffusers/pipelines/pia/pipeline_pia.py +30 -37
  139. diffusers/pipelines/pipeline_flax_utils.py +4 -9
  140. diffusers/pipelines/pipeline_loading_utils.py +0 -3
  141. diffusers/pipelines/pipeline_utils.py +2 -14
  142. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
  143. diffusers/pipelines/stable_audio/__init__.py +50 -0
  144. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  145. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
  146. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
  147. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
  151. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
  152. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
  153. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
  154. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
  155. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
  156. diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
  157. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
  158. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
  159. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
  160. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
  161. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
  162. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
  163. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
  164. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
  165. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
  166. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
  167. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
  168. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
  171. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
  172. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
  175. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
  179. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  180. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  181. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
  182. diffusers/schedulers/__init__.py +8 -0
  183. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  184. diffusers/schedulers/scheduling_ddim.py +1 -1
  185. diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
  186. diffusers/schedulers/scheduling_ddpm.py +1 -1
  187. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
  188. diffusers/schedulers/scheduling_deis_multistep.py +2 -2
  189. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  190. diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
  191. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
  192. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
  193. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
  194. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
  195. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
  196. diffusers/schedulers/scheduling_ipndm.py +1 -1
  197. diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
  198. diffusers/schedulers/scheduling_utils.py +1 -3
  199. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  200. diffusers/training_utils.py +99 -14
  201. diffusers/utils/__init__.py +2 -2
  202. diffusers/utils/dummy_pt_objects.py +210 -0
  203. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  204. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  205. diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
  206. diffusers/utils/dynamic_modules_utils.py +1 -11
  207. diffusers/utils/export_utils.py +50 -6
  208. diffusers/utils/hub_utils.py +45 -42
  209. diffusers/utils/import_utils.py +37 -15
  210. diffusers/utils/loading_utils.py +80 -3
  211. diffusers/utils/testing_utils.py +11 -8
  212. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/METADATA +73 -83
  213. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/RECORD +217 -164
  214. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/WHEEL +1 -1
  215. diffusers/loaders/autoencoder.py +0 -146
  216. diffusers/loaders/controlnet.py +0 -136
  217. diffusers/loaders/lora.py +0 -1728
  218. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/LICENSE +0 -0
  219. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/entry_points.txt +0 -0
  220. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1271 @@
1
+ # Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from ...configuration_utils import ConfigMixin, register_to_config
24
+ from ...loaders.single_file_model import FromOriginalModelMixin
25
+ from ...utils import logging
26
+ from ...utils.accelerate_utils import apply_forward_hook
27
+ from ..activations import get_activation
28
+ from ..downsampling import CogVideoXDownsample3D
29
+ from ..modeling_outputs import AutoencoderKLOutput
30
+ from ..modeling_utils import ModelMixin
31
+ from ..upsampling import CogVideoXUpsample3D
32
+ from .vae import DecoderOutput, DiagonalGaussianDistribution
33
+
34
+
35
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
36
+
37
+
38
+ class CogVideoXSafeConv3d(nn.Conv3d):
39
+ r"""
40
+ A 3D convolution layer that splits the input tensor into smaller parts to avoid OOM in CogVideoX Model.
41
+ """
42
+
43
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
44
+ memory_count = torch.prod(torch.tensor(input.shape)).item() * 2 / 1024**3
45
+
46
+ # Set to 2GB, suitable for CuDNN
47
+ if memory_count > 2:
48
+ kernel_size = self.kernel_size[0]
49
+ part_num = int(memory_count / 2) + 1
50
+ input_chunks = torch.chunk(input, part_num, dim=2)
51
+
52
+ if kernel_size > 1:
53
+ input_chunks = [input_chunks[0]] + [
54
+ torch.cat((input_chunks[i - 1][:, :, -kernel_size + 1 :], input_chunks[i]), dim=2)
55
+ for i in range(1, len(input_chunks))
56
+ ]
57
+
58
+ output_chunks = []
59
+ for input_chunk in input_chunks:
60
+ output_chunks.append(super().forward(input_chunk))
61
+ output = torch.cat(output_chunks, dim=2)
62
+ return output
63
+ else:
64
+ return super().forward(input)
65
+
66
+
67
+ class CogVideoXCausalConv3d(nn.Module):
68
+ r"""A 3D causal convolution layer that pads the input tensor to ensure causality in CogVideoX Model.
69
+
70
+ Args:
71
+ in_channels (`int`): Number of channels in the input tensor.
72
+ out_channels (`int`): Number of output channels produced by the convolution.
73
+ kernel_size (`int` or `Tuple[int, int, int]`): Kernel size of the convolutional kernel.
74
+ stride (`int`, defaults to `1`): Stride of the convolution.
75
+ dilation (`int`, defaults to `1`): Dilation rate of the convolution.
76
+ pad_mode (`str`, defaults to `"constant"`): Padding mode.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ in_channels: int,
82
+ out_channels: int,
83
+ kernel_size: Union[int, Tuple[int, int, int]],
84
+ stride: int = 1,
85
+ dilation: int = 1,
86
+ pad_mode: str = "constant",
87
+ ):
88
+ super().__init__()
89
+
90
+ if isinstance(kernel_size, int):
91
+ kernel_size = (kernel_size,) * 3
92
+
93
+ time_kernel_size, height_kernel_size, width_kernel_size = kernel_size
94
+
95
+ self.pad_mode = pad_mode
96
+ time_pad = dilation * (time_kernel_size - 1) + (1 - stride)
97
+ height_pad = height_kernel_size // 2
98
+ width_pad = width_kernel_size // 2
99
+
100
+ self.height_pad = height_pad
101
+ self.width_pad = width_pad
102
+ self.time_pad = time_pad
103
+ self.time_causal_padding = (width_pad, width_pad, height_pad, height_pad, time_pad, 0)
104
+
105
+ self.temporal_dim = 2
106
+ self.time_kernel_size = time_kernel_size
107
+
108
+ stride = (stride, 1, 1)
109
+ dilation = (dilation, 1, 1)
110
+ self.conv = CogVideoXSafeConv3d(
111
+ in_channels=in_channels,
112
+ out_channels=out_channels,
113
+ kernel_size=kernel_size,
114
+ stride=stride,
115
+ dilation=dilation,
116
+ )
117
+
118
+ self.conv_cache = None
119
+
120
+ def fake_context_parallel_forward(self, inputs: torch.Tensor) -> torch.Tensor:
121
+ kernel_size = self.time_kernel_size
122
+ if kernel_size > 1:
123
+ cached_inputs = (
124
+ [self.conv_cache] if self.conv_cache is not None else [inputs[:, :, :1]] * (kernel_size - 1)
125
+ )
126
+ inputs = torch.cat(cached_inputs + [inputs], dim=2)
127
+ return inputs
128
+
129
+ def _clear_fake_context_parallel_cache(self):
130
+ del self.conv_cache
131
+ self.conv_cache = None
132
+
133
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
134
+ inputs = self.fake_context_parallel_forward(inputs)
135
+
136
+ self._clear_fake_context_parallel_cache()
137
+ # Note: we could move these to the cpu for a lower maximum memory usage but its only a few
138
+ # hundred megabytes and so let's not do it for now
139
+ self.conv_cache = inputs[:, :, -self.time_kernel_size + 1 :].clone()
140
+
141
+ padding_2d = (self.width_pad, self.width_pad, self.height_pad, self.height_pad)
142
+ inputs = F.pad(inputs, padding_2d, mode="constant", value=0)
143
+
144
+ output = self.conv(inputs)
145
+ return output
146
+
147
+
148
+ class CogVideoXSpatialNorm3D(nn.Module):
149
+ r"""
150
+ Spatially conditioned normalization as defined in https://arxiv.org/abs/2209.09002. This implementation is specific
151
+ to 3D-video like data.
152
+
153
+ CogVideoXSafeConv3d is used instead of nn.Conv3d to avoid OOM in CogVideoX Model.
154
+
155
+ Args:
156
+ f_channels (`int`):
157
+ The number of channels for input to group normalization layer, and output of the spatial norm layer.
158
+ zq_channels (`int`):
159
+ The number of channels for the quantized vector as described in the paper.
160
+ groups (`int`):
161
+ Number of groups to separate the channels into for group normalization.
162
+ """
163
+
164
+ def __init__(
165
+ self,
166
+ f_channels: int,
167
+ zq_channels: int,
168
+ groups: int = 32,
169
+ ):
170
+ super().__init__()
171
+ self.norm_layer = nn.GroupNorm(num_channels=f_channels, num_groups=groups, eps=1e-6, affine=True)
172
+ self.conv_y = CogVideoXCausalConv3d(zq_channels, f_channels, kernel_size=1, stride=1)
173
+ self.conv_b = CogVideoXCausalConv3d(zq_channels, f_channels, kernel_size=1, stride=1)
174
+
175
+ def forward(self, f: torch.Tensor, zq: torch.Tensor) -> torch.Tensor:
176
+ if f.shape[2] > 1 and f.shape[2] % 2 == 1:
177
+ f_first, f_rest = f[:, :, :1], f[:, :, 1:]
178
+ f_first_size, f_rest_size = f_first.shape[-3:], f_rest.shape[-3:]
179
+ z_first, z_rest = zq[:, :, :1], zq[:, :, 1:]
180
+ z_first = F.interpolate(z_first, size=f_first_size)
181
+ z_rest = F.interpolate(z_rest, size=f_rest_size)
182
+ zq = torch.cat([z_first, z_rest], dim=2)
183
+ else:
184
+ zq = F.interpolate(zq, size=f.shape[-3:])
185
+
186
+ norm_f = self.norm_layer(f)
187
+ new_f = norm_f * self.conv_y(zq) + self.conv_b(zq)
188
+ return new_f
189
+
190
+
191
+ class CogVideoXResnetBlock3D(nn.Module):
192
+ r"""
193
+ A 3D ResNet block used in the CogVideoX model.
194
+
195
+ Args:
196
+ in_channels (`int`):
197
+ Number of input channels.
198
+ out_channels (`int`, *optional*):
199
+ Number of output channels. If None, defaults to `in_channels`.
200
+ dropout (`float`, defaults to `0.0`):
201
+ Dropout rate.
202
+ temb_channels (`int`, defaults to `512`):
203
+ Number of time embedding channels.
204
+ groups (`int`, defaults to `32`):
205
+ Number of groups to separate the channels into for group normalization.
206
+ eps (`float`, defaults to `1e-6`):
207
+ Epsilon value for normalization layers.
208
+ non_linearity (`str`, defaults to `"swish"`):
209
+ Activation function to use.
210
+ conv_shortcut (bool, defaults to `False`):
211
+ Whether or not to use a convolution shortcut.
212
+ spatial_norm_dim (`int`, *optional*):
213
+ The dimension to use for spatial norm if it is to be used instead of group norm.
214
+ pad_mode (str, defaults to `"first"`):
215
+ Padding mode.
216
+ """
217
+
218
+ def __init__(
219
+ self,
220
+ in_channels: int,
221
+ out_channels: Optional[int] = None,
222
+ dropout: float = 0.0,
223
+ temb_channels: int = 512,
224
+ groups: int = 32,
225
+ eps: float = 1e-6,
226
+ non_linearity: str = "swish",
227
+ conv_shortcut: bool = False,
228
+ spatial_norm_dim: Optional[int] = None,
229
+ pad_mode: str = "first",
230
+ ):
231
+ super().__init__()
232
+
233
+ out_channels = out_channels or in_channels
234
+
235
+ self.in_channels = in_channels
236
+ self.out_channels = out_channels
237
+ self.nonlinearity = get_activation(non_linearity)
238
+ self.use_conv_shortcut = conv_shortcut
239
+
240
+ if spatial_norm_dim is None:
241
+ self.norm1 = nn.GroupNorm(num_channels=in_channels, num_groups=groups, eps=eps)
242
+ self.norm2 = nn.GroupNorm(num_channels=out_channels, num_groups=groups, eps=eps)
243
+ else:
244
+ self.norm1 = CogVideoXSpatialNorm3D(
245
+ f_channels=in_channels,
246
+ zq_channels=spatial_norm_dim,
247
+ groups=groups,
248
+ )
249
+ self.norm2 = CogVideoXSpatialNorm3D(
250
+ f_channels=out_channels,
251
+ zq_channels=spatial_norm_dim,
252
+ groups=groups,
253
+ )
254
+
255
+ self.conv1 = CogVideoXCausalConv3d(
256
+ in_channels=in_channels, out_channels=out_channels, kernel_size=3, pad_mode=pad_mode
257
+ )
258
+
259
+ if temb_channels > 0:
260
+ self.temb_proj = nn.Linear(in_features=temb_channels, out_features=out_channels)
261
+
262
+ self.dropout = nn.Dropout(dropout)
263
+ self.conv2 = CogVideoXCausalConv3d(
264
+ in_channels=out_channels, out_channels=out_channels, kernel_size=3, pad_mode=pad_mode
265
+ )
266
+
267
+ if self.in_channels != self.out_channels:
268
+ if self.use_conv_shortcut:
269
+ self.conv_shortcut = CogVideoXCausalConv3d(
270
+ in_channels=in_channels, out_channels=out_channels, kernel_size=3, pad_mode=pad_mode
271
+ )
272
+ else:
273
+ self.conv_shortcut = CogVideoXSafeConv3d(
274
+ in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0
275
+ )
276
+
277
+ def forward(
278
+ self,
279
+ inputs: torch.Tensor,
280
+ temb: Optional[torch.Tensor] = None,
281
+ zq: Optional[torch.Tensor] = None,
282
+ ) -> torch.Tensor:
283
+ hidden_states = inputs
284
+
285
+ if zq is not None:
286
+ hidden_states = self.norm1(hidden_states, zq)
287
+ else:
288
+ hidden_states = self.norm1(hidden_states)
289
+
290
+ hidden_states = self.nonlinearity(hidden_states)
291
+ hidden_states = self.conv1(hidden_states)
292
+
293
+ if temb is not None:
294
+ hidden_states = hidden_states + self.temb_proj(self.nonlinearity(temb))[:, :, None, None, None]
295
+
296
+ if zq is not None:
297
+ hidden_states = self.norm2(hidden_states, zq)
298
+ else:
299
+ hidden_states = self.norm2(hidden_states)
300
+
301
+ hidden_states = self.nonlinearity(hidden_states)
302
+ hidden_states = self.dropout(hidden_states)
303
+ hidden_states = self.conv2(hidden_states)
304
+
305
+ if self.in_channels != self.out_channels:
306
+ inputs = self.conv_shortcut(inputs)
307
+
308
+ hidden_states = hidden_states + inputs
309
+ return hidden_states
310
+
311
+
312
+ class CogVideoXDownBlock3D(nn.Module):
313
+ r"""
314
+ A downsampling block used in the CogVideoX model.
315
+
316
+ Args:
317
+ in_channels (`int`):
318
+ Number of input channels.
319
+ out_channels (`int`, *optional*):
320
+ Number of output channels. If None, defaults to `in_channels`.
321
+ temb_channels (`int`, defaults to `512`):
322
+ Number of time embedding channels.
323
+ num_layers (`int`, defaults to `1`):
324
+ Number of resnet layers.
325
+ dropout (`float`, defaults to `0.0`):
326
+ Dropout rate.
327
+ resnet_eps (`float`, defaults to `1e-6`):
328
+ Epsilon value for normalization layers.
329
+ resnet_act_fn (`str`, defaults to `"swish"`):
330
+ Activation function to use.
331
+ resnet_groups (`int`, defaults to `32`):
332
+ Number of groups to separate the channels into for group normalization.
333
+ add_downsample (`bool`, defaults to `True`):
334
+ Whether or not to use a downsampling layer. If not used, output dimension would be same as input dimension.
335
+ compress_time (`bool`, defaults to `False`):
336
+ Whether or not to downsample across temporal dimension.
337
+ pad_mode (str, defaults to `"first"`):
338
+ Padding mode.
339
+ """
340
+
341
+ _supports_gradient_checkpointing = True
342
+
343
+ def __init__(
344
+ self,
345
+ in_channels: int,
346
+ out_channels: int,
347
+ temb_channels: int,
348
+ dropout: float = 0.0,
349
+ num_layers: int = 1,
350
+ resnet_eps: float = 1e-6,
351
+ resnet_act_fn: str = "swish",
352
+ resnet_groups: int = 32,
353
+ add_downsample: bool = True,
354
+ downsample_padding: int = 0,
355
+ compress_time: bool = False,
356
+ pad_mode: str = "first",
357
+ ):
358
+ super().__init__()
359
+
360
+ resnets = []
361
+ for i in range(num_layers):
362
+ in_channel = in_channels if i == 0 else out_channels
363
+ resnets.append(
364
+ CogVideoXResnetBlock3D(
365
+ in_channels=in_channel,
366
+ out_channels=out_channels,
367
+ dropout=dropout,
368
+ temb_channels=temb_channels,
369
+ groups=resnet_groups,
370
+ eps=resnet_eps,
371
+ non_linearity=resnet_act_fn,
372
+ pad_mode=pad_mode,
373
+ )
374
+ )
375
+
376
+ self.resnets = nn.ModuleList(resnets)
377
+ self.downsamplers = None
378
+
379
+ if add_downsample:
380
+ self.downsamplers = nn.ModuleList(
381
+ [
382
+ CogVideoXDownsample3D(
383
+ out_channels, out_channels, padding=downsample_padding, compress_time=compress_time
384
+ )
385
+ ]
386
+ )
387
+
388
+ self.gradient_checkpointing = False
389
+
390
+ def forward(
391
+ self,
392
+ hidden_states: torch.Tensor,
393
+ temb: Optional[torch.Tensor] = None,
394
+ zq: Optional[torch.Tensor] = None,
395
+ ) -> torch.Tensor:
396
+ for resnet in self.resnets:
397
+ if self.training and self.gradient_checkpointing:
398
+
399
+ def create_custom_forward(module):
400
+ def create_forward(*inputs):
401
+ return module(*inputs)
402
+
403
+ return create_forward
404
+
405
+ hidden_states = torch.utils.checkpoint.checkpoint(
406
+ create_custom_forward(resnet), hidden_states, temb, zq
407
+ )
408
+ else:
409
+ hidden_states = resnet(hidden_states, temb, zq)
410
+
411
+ if self.downsamplers is not None:
412
+ for downsampler in self.downsamplers:
413
+ hidden_states = downsampler(hidden_states)
414
+
415
+ return hidden_states
416
+
417
+
418
+ class CogVideoXMidBlock3D(nn.Module):
419
+ r"""
420
+ A middle block used in the CogVideoX model.
421
+
422
+ Args:
423
+ in_channels (`int`):
424
+ Number of input channels.
425
+ temb_channels (`int`, defaults to `512`):
426
+ Number of time embedding channels.
427
+ dropout (`float`, defaults to `0.0`):
428
+ Dropout rate.
429
+ num_layers (`int`, defaults to `1`):
430
+ Number of resnet layers.
431
+ resnet_eps (`float`, defaults to `1e-6`):
432
+ Epsilon value for normalization layers.
433
+ resnet_act_fn (`str`, defaults to `"swish"`):
434
+ Activation function to use.
435
+ resnet_groups (`int`, defaults to `32`):
436
+ Number of groups to separate the channels into for group normalization.
437
+ spatial_norm_dim (`int`, *optional*):
438
+ The dimension to use for spatial norm if it is to be used instead of group norm.
439
+ pad_mode (str, defaults to `"first"`):
440
+ Padding mode.
441
+ """
442
+
443
+ _supports_gradient_checkpointing = True
444
+
445
+ def __init__(
446
+ self,
447
+ in_channels: int,
448
+ temb_channels: int,
449
+ dropout: float = 0.0,
450
+ num_layers: int = 1,
451
+ resnet_eps: float = 1e-6,
452
+ resnet_act_fn: str = "swish",
453
+ resnet_groups: int = 32,
454
+ spatial_norm_dim: Optional[int] = None,
455
+ pad_mode: str = "first",
456
+ ):
457
+ super().__init__()
458
+
459
+ resnets = []
460
+ for _ in range(num_layers):
461
+ resnets.append(
462
+ CogVideoXResnetBlock3D(
463
+ in_channels=in_channels,
464
+ out_channels=in_channels,
465
+ dropout=dropout,
466
+ temb_channels=temb_channels,
467
+ groups=resnet_groups,
468
+ eps=resnet_eps,
469
+ spatial_norm_dim=spatial_norm_dim,
470
+ non_linearity=resnet_act_fn,
471
+ pad_mode=pad_mode,
472
+ )
473
+ )
474
+ self.resnets = nn.ModuleList(resnets)
475
+
476
+ self.gradient_checkpointing = False
477
+
478
+ def forward(
479
+ self,
480
+ hidden_states: torch.Tensor,
481
+ temb: Optional[torch.Tensor] = None,
482
+ zq: Optional[torch.Tensor] = None,
483
+ ) -> torch.Tensor:
484
+ for resnet in self.resnets:
485
+ if self.training and self.gradient_checkpointing:
486
+
487
+ def create_custom_forward(module):
488
+ def create_forward(*inputs):
489
+ return module(*inputs)
490
+
491
+ return create_forward
492
+
493
+ hidden_states = torch.utils.checkpoint.checkpoint(
494
+ create_custom_forward(resnet), hidden_states, temb, zq
495
+ )
496
+ else:
497
+ hidden_states = resnet(hidden_states, temb, zq)
498
+
499
+ return hidden_states
500
+
501
+
502
+ class CogVideoXUpBlock3D(nn.Module):
503
+ r"""
504
+ An upsampling block used in the CogVideoX model.
505
+
506
+ Args:
507
+ in_channels (`int`):
508
+ Number of input channels.
509
+ out_channels (`int`, *optional*):
510
+ Number of output channels. If None, defaults to `in_channels`.
511
+ temb_channels (`int`, defaults to `512`):
512
+ Number of time embedding channels.
513
+ dropout (`float`, defaults to `0.0`):
514
+ Dropout rate.
515
+ num_layers (`int`, defaults to `1`):
516
+ Number of resnet layers.
517
+ resnet_eps (`float`, defaults to `1e-6`):
518
+ Epsilon value for normalization layers.
519
+ resnet_act_fn (`str`, defaults to `"swish"`):
520
+ Activation function to use.
521
+ resnet_groups (`int`, defaults to `32`):
522
+ Number of groups to separate the channels into for group normalization.
523
+ spatial_norm_dim (`int`, defaults to `16`):
524
+ The dimension to use for spatial norm if it is to be used instead of group norm.
525
+ add_upsample (`bool`, defaults to `True`):
526
+ Whether or not to use a upsampling layer. If not used, output dimension would be same as input dimension.
527
+ compress_time (`bool`, defaults to `False`):
528
+ Whether or not to downsample across temporal dimension.
529
+ pad_mode (str, defaults to `"first"`):
530
+ Padding mode.
531
+ """
532
+
533
+ def __init__(
534
+ self,
535
+ in_channels: int,
536
+ out_channels: int,
537
+ temb_channels: int,
538
+ dropout: float = 0.0,
539
+ num_layers: int = 1,
540
+ resnet_eps: float = 1e-6,
541
+ resnet_act_fn: str = "swish",
542
+ resnet_groups: int = 32,
543
+ spatial_norm_dim: int = 16,
544
+ add_upsample: bool = True,
545
+ upsample_padding: int = 1,
546
+ compress_time: bool = False,
547
+ pad_mode: str = "first",
548
+ ):
549
+ super().__init__()
550
+
551
+ resnets = []
552
+ for i in range(num_layers):
553
+ in_channel = in_channels if i == 0 else out_channels
554
+ resnets.append(
555
+ CogVideoXResnetBlock3D(
556
+ in_channels=in_channel,
557
+ out_channels=out_channels,
558
+ dropout=dropout,
559
+ temb_channels=temb_channels,
560
+ groups=resnet_groups,
561
+ eps=resnet_eps,
562
+ non_linearity=resnet_act_fn,
563
+ spatial_norm_dim=spatial_norm_dim,
564
+ pad_mode=pad_mode,
565
+ )
566
+ )
567
+
568
+ self.resnets = nn.ModuleList(resnets)
569
+ self.upsamplers = None
570
+
571
+ if add_upsample:
572
+ self.upsamplers = nn.ModuleList(
573
+ [
574
+ CogVideoXUpsample3D(
575
+ out_channels, out_channels, padding=upsample_padding, compress_time=compress_time
576
+ )
577
+ ]
578
+ )
579
+
580
+ self.gradient_checkpointing = False
581
+
582
+ def forward(
583
+ self,
584
+ hidden_states: torch.Tensor,
585
+ temb: Optional[torch.Tensor] = None,
586
+ zq: Optional[torch.Tensor] = None,
587
+ ) -> torch.Tensor:
588
+ r"""Forward method of the `CogVideoXUpBlock3D` class."""
589
+ for resnet in self.resnets:
590
+ if self.training and self.gradient_checkpointing:
591
+
592
+ def create_custom_forward(module):
593
+ def create_forward(*inputs):
594
+ return module(*inputs)
595
+
596
+ return create_forward
597
+
598
+ hidden_states = torch.utils.checkpoint.checkpoint(
599
+ create_custom_forward(resnet), hidden_states, temb, zq
600
+ )
601
+ else:
602
+ hidden_states = resnet(hidden_states, temb, zq)
603
+
604
+ if self.upsamplers is not None:
605
+ for upsampler in self.upsamplers:
606
+ hidden_states = upsampler(hidden_states)
607
+
608
+ return hidden_states
609
+
610
+
611
+ class CogVideoXEncoder3D(nn.Module):
612
+ r"""
613
+ The `CogVideoXEncoder3D` layer of a variational autoencoder that encodes its input into a latent representation.
614
+
615
+ Args:
616
+ in_channels (`int`, *optional*, defaults to 3):
617
+ The number of input channels.
618
+ out_channels (`int`, *optional*, defaults to 3):
619
+ The number of output channels.
620
+ down_block_types (`Tuple[str, ...]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
621
+ The types of down blocks to use. See `~diffusers.models.unet_2d_blocks.get_down_block` for available
622
+ options.
623
+ block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
624
+ The number of output channels for each block.
625
+ act_fn (`str`, *optional*, defaults to `"silu"`):
626
+ The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
627
+ layers_per_block (`int`, *optional*, defaults to 2):
628
+ The number of layers per block.
629
+ norm_num_groups (`int`, *optional*, defaults to 32):
630
+ The number of groups for normalization.
631
+ """
632
+
633
+ _supports_gradient_checkpointing = True
634
+
635
+ def __init__(
636
+ self,
637
+ in_channels: int = 3,
638
+ out_channels: int = 16,
639
+ down_block_types: Tuple[str, ...] = (
640
+ "CogVideoXDownBlock3D",
641
+ "CogVideoXDownBlock3D",
642
+ "CogVideoXDownBlock3D",
643
+ "CogVideoXDownBlock3D",
644
+ ),
645
+ block_out_channels: Tuple[int, ...] = (128, 256, 256, 512),
646
+ layers_per_block: int = 3,
647
+ act_fn: str = "silu",
648
+ norm_eps: float = 1e-6,
649
+ norm_num_groups: int = 32,
650
+ dropout: float = 0.0,
651
+ pad_mode: str = "first",
652
+ temporal_compression_ratio: float = 4,
653
+ ):
654
+ super().__init__()
655
+
656
+ # log2 of temporal_compress_times
657
+ temporal_compress_level = int(np.log2(temporal_compression_ratio))
658
+
659
+ self.conv_in = CogVideoXCausalConv3d(in_channels, block_out_channels[0], kernel_size=3, pad_mode=pad_mode)
660
+ self.down_blocks = nn.ModuleList([])
661
+
662
+ # down blocks
663
+ output_channel = block_out_channels[0]
664
+ for i, down_block_type in enumerate(down_block_types):
665
+ input_channel = output_channel
666
+ output_channel = block_out_channels[i]
667
+ is_final_block = i == len(block_out_channels) - 1
668
+ compress_time = i < temporal_compress_level
669
+
670
+ if down_block_type == "CogVideoXDownBlock3D":
671
+ down_block = CogVideoXDownBlock3D(
672
+ in_channels=input_channel,
673
+ out_channels=output_channel,
674
+ temb_channels=0,
675
+ dropout=dropout,
676
+ num_layers=layers_per_block,
677
+ resnet_eps=norm_eps,
678
+ resnet_act_fn=act_fn,
679
+ resnet_groups=norm_num_groups,
680
+ add_downsample=not is_final_block,
681
+ compress_time=compress_time,
682
+ )
683
+ else:
684
+ raise ValueError("Invalid `down_block_type` encountered. Must be `CogVideoXDownBlock3D`")
685
+
686
+ self.down_blocks.append(down_block)
687
+
688
+ # mid block
689
+ self.mid_block = CogVideoXMidBlock3D(
690
+ in_channels=block_out_channels[-1],
691
+ temb_channels=0,
692
+ dropout=dropout,
693
+ num_layers=2,
694
+ resnet_eps=norm_eps,
695
+ resnet_act_fn=act_fn,
696
+ resnet_groups=norm_num_groups,
697
+ pad_mode=pad_mode,
698
+ )
699
+
700
+ self.norm_out = nn.GroupNorm(norm_num_groups, block_out_channels[-1], eps=1e-6)
701
+ self.conv_act = nn.SiLU()
702
+ self.conv_out = CogVideoXCausalConv3d(
703
+ block_out_channels[-1], 2 * out_channels, kernel_size=3, pad_mode=pad_mode
704
+ )
705
+
706
+ self.gradient_checkpointing = False
707
+
708
+ def forward(self, sample: torch.Tensor, temb: Optional[torch.Tensor] = None) -> torch.Tensor:
709
+ r"""The forward method of the `CogVideoXEncoder3D` class."""
710
+ hidden_states = self.conv_in(sample)
711
+
712
+ if self.training and self.gradient_checkpointing:
713
+
714
+ def create_custom_forward(module):
715
+ def custom_forward(*inputs):
716
+ return module(*inputs)
717
+
718
+ return custom_forward
719
+
720
+ # 1. Down
721
+ for down_block in self.down_blocks:
722
+ hidden_states = torch.utils.checkpoint.checkpoint(
723
+ create_custom_forward(down_block), hidden_states, temb, None
724
+ )
725
+
726
+ # 2. Mid
727
+ hidden_states = torch.utils.checkpoint.checkpoint(
728
+ create_custom_forward(self.mid_block), hidden_states, temb, None
729
+ )
730
+ else:
731
+ # 1. Down
732
+ for down_block in self.down_blocks:
733
+ hidden_states = down_block(hidden_states, temb, None)
734
+
735
+ # 2. Mid
736
+ hidden_states = self.mid_block(hidden_states, temb, None)
737
+
738
+ # 3. Post-process
739
+ hidden_states = self.norm_out(hidden_states)
740
+ hidden_states = self.conv_act(hidden_states)
741
+ hidden_states = self.conv_out(hidden_states)
742
+ return hidden_states
743
+
744
+
745
+ class CogVideoXDecoder3D(nn.Module):
746
+ r"""
747
+ The `CogVideoXDecoder3D` layer of a variational autoencoder that decodes its latent representation into an output
748
+ sample.
749
+
750
+ Args:
751
+ in_channels (`int`, *optional*, defaults to 3):
752
+ The number of input channels.
753
+ out_channels (`int`, *optional*, defaults to 3):
754
+ The number of output channels.
755
+ up_block_types (`Tuple[str, ...]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
756
+ The types of up blocks to use. See `~diffusers.models.unet_2d_blocks.get_up_block` for available options.
757
+ block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
758
+ The number of output channels for each block.
759
+ act_fn (`str`, *optional*, defaults to `"silu"`):
760
+ The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
761
+ layers_per_block (`int`, *optional*, defaults to 2):
762
+ The number of layers per block.
763
+ norm_num_groups (`int`, *optional*, defaults to 32):
764
+ The number of groups for normalization.
765
+ """
766
+
767
+ _supports_gradient_checkpointing = True
768
+
769
+ def __init__(
770
+ self,
771
+ in_channels: int = 16,
772
+ out_channels: int = 3,
773
+ up_block_types: Tuple[str, ...] = (
774
+ "CogVideoXUpBlock3D",
775
+ "CogVideoXUpBlock3D",
776
+ "CogVideoXUpBlock3D",
777
+ "CogVideoXUpBlock3D",
778
+ ),
779
+ block_out_channels: Tuple[int, ...] = (128, 256, 256, 512),
780
+ layers_per_block: int = 3,
781
+ act_fn: str = "silu",
782
+ norm_eps: float = 1e-6,
783
+ norm_num_groups: int = 32,
784
+ dropout: float = 0.0,
785
+ pad_mode: str = "first",
786
+ temporal_compression_ratio: float = 4,
787
+ ):
788
+ super().__init__()
789
+
790
+ reversed_block_out_channels = list(reversed(block_out_channels))
791
+
792
+ self.conv_in = CogVideoXCausalConv3d(
793
+ in_channels, reversed_block_out_channels[0], kernel_size=3, pad_mode=pad_mode
794
+ )
795
+
796
+ # mid block
797
+ self.mid_block = CogVideoXMidBlock3D(
798
+ in_channels=reversed_block_out_channels[0],
799
+ temb_channels=0,
800
+ num_layers=2,
801
+ resnet_eps=norm_eps,
802
+ resnet_act_fn=act_fn,
803
+ resnet_groups=norm_num_groups,
804
+ spatial_norm_dim=in_channels,
805
+ pad_mode=pad_mode,
806
+ )
807
+
808
+ # up blocks
809
+ self.up_blocks = nn.ModuleList([])
810
+
811
+ output_channel = reversed_block_out_channels[0]
812
+ temporal_compress_level = int(np.log2(temporal_compression_ratio))
813
+
814
+ for i, up_block_type in enumerate(up_block_types):
815
+ prev_output_channel = output_channel
816
+ output_channel = reversed_block_out_channels[i]
817
+ is_final_block = i == len(block_out_channels) - 1
818
+ compress_time = i < temporal_compress_level
819
+
820
+ if up_block_type == "CogVideoXUpBlock3D":
821
+ up_block = CogVideoXUpBlock3D(
822
+ in_channels=prev_output_channel,
823
+ out_channels=output_channel,
824
+ temb_channels=0,
825
+ dropout=dropout,
826
+ num_layers=layers_per_block + 1,
827
+ resnet_eps=norm_eps,
828
+ resnet_act_fn=act_fn,
829
+ resnet_groups=norm_num_groups,
830
+ spatial_norm_dim=in_channels,
831
+ add_upsample=not is_final_block,
832
+ compress_time=compress_time,
833
+ pad_mode=pad_mode,
834
+ )
835
+ prev_output_channel = output_channel
836
+ else:
837
+ raise ValueError("Invalid `up_block_type` encountered. Must be `CogVideoXUpBlock3D`")
838
+
839
+ self.up_blocks.append(up_block)
840
+
841
+ self.norm_out = CogVideoXSpatialNorm3D(reversed_block_out_channels[-1], in_channels, groups=norm_num_groups)
842
+ self.conv_act = nn.SiLU()
843
+ self.conv_out = CogVideoXCausalConv3d(
844
+ reversed_block_out_channels[-1], out_channels, kernel_size=3, pad_mode=pad_mode
845
+ )
846
+
847
+ self.gradient_checkpointing = False
848
+
849
+ def forward(self, sample: torch.Tensor, temb: Optional[torch.Tensor] = None) -> torch.Tensor:
850
+ r"""The forward method of the `CogVideoXDecoder3D` class."""
851
+ hidden_states = self.conv_in(sample)
852
+
853
+ if self.training and self.gradient_checkpointing:
854
+
855
+ def create_custom_forward(module):
856
+ def custom_forward(*inputs):
857
+ return module(*inputs)
858
+
859
+ return custom_forward
860
+
861
+ # 1. Mid
862
+ hidden_states = torch.utils.checkpoint.checkpoint(
863
+ create_custom_forward(self.mid_block), hidden_states, temb, sample
864
+ )
865
+
866
+ # 2. Up
867
+ for up_block in self.up_blocks:
868
+ hidden_states = torch.utils.checkpoint.checkpoint(
869
+ create_custom_forward(up_block), hidden_states, temb, sample
870
+ )
871
+ else:
872
+ # 1. Mid
873
+ hidden_states = self.mid_block(hidden_states, temb, sample)
874
+
875
+ # 2. Up
876
+ for up_block in self.up_blocks:
877
+ hidden_states = up_block(hidden_states, temb, sample)
878
+
879
+ # 3. Post-process
880
+ hidden_states = self.norm_out(hidden_states, sample)
881
+ hidden_states = self.conv_act(hidden_states)
882
+ hidden_states = self.conv_out(hidden_states)
883
+ return hidden_states
884
+
885
+
886
+ class AutoencoderKLCogVideoX(ModelMixin, ConfigMixin, FromOriginalModelMixin):
887
+ r"""
888
+ A VAE model with KL loss for encoding images into latents and decoding latent representations into images. Used in
889
+ [CogVideoX](https://github.com/THUDM/CogVideo).
890
+
891
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
892
+ for all models (such as downloading or saving).
893
+
894
+ Parameters:
895
+ in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
896
+ out_channels (int, *optional*, defaults to 3): Number of channels in the output.
897
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
898
+ Tuple of downsample block types.
899
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
900
+ Tuple of upsample block types.
901
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
902
+ Tuple of block output channels.
903
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
904
+ sample_size (`int`, *optional*, defaults to `32`): Sample input size.
905
+ scaling_factor (`float`, *optional*, defaults to `1.15258426`):
906
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
907
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
908
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
909
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
910
+ / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
911
+ Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
912
+ force_upcast (`bool`, *optional*, default to `True`):
913
+ If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
914
+ can be fine-tuned / trained to a lower range without loosing too much precision in which case
915
+ `force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
916
+ """
917
+
918
+ _supports_gradient_checkpointing = True
919
+ _no_split_modules = ["CogVideoXResnetBlock3D"]
920
+
921
+ @register_to_config
922
+ def __init__(
923
+ self,
924
+ in_channels: int = 3,
925
+ out_channels: int = 3,
926
+ down_block_types: Tuple[str] = (
927
+ "CogVideoXDownBlock3D",
928
+ "CogVideoXDownBlock3D",
929
+ "CogVideoXDownBlock3D",
930
+ "CogVideoXDownBlock3D",
931
+ ),
932
+ up_block_types: Tuple[str] = (
933
+ "CogVideoXUpBlock3D",
934
+ "CogVideoXUpBlock3D",
935
+ "CogVideoXUpBlock3D",
936
+ "CogVideoXUpBlock3D",
937
+ ),
938
+ block_out_channels: Tuple[int] = (128, 256, 256, 512),
939
+ latent_channels: int = 16,
940
+ layers_per_block: int = 3,
941
+ act_fn: str = "silu",
942
+ norm_eps: float = 1e-6,
943
+ norm_num_groups: int = 32,
944
+ temporal_compression_ratio: float = 4,
945
+ sample_height: int = 480,
946
+ sample_width: int = 720,
947
+ scaling_factor: float = 1.15258426,
948
+ shift_factor: Optional[float] = None,
949
+ latents_mean: Optional[Tuple[float]] = None,
950
+ latents_std: Optional[Tuple[float]] = None,
951
+ force_upcast: float = True,
952
+ use_quant_conv: bool = False,
953
+ use_post_quant_conv: bool = False,
954
+ ):
955
+ super().__init__()
956
+
957
+ self.encoder = CogVideoXEncoder3D(
958
+ in_channels=in_channels,
959
+ out_channels=latent_channels,
960
+ down_block_types=down_block_types,
961
+ block_out_channels=block_out_channels,
962
+ layers_per_block=layers_per_block,
963
+ act_fn=act_fn,
964
+ norm_eps=norm_eps,
965
+ norm_num_groups=norm_num_groups,
966
+ temporal_compression_ratio=temporal_compression_ratio,
967
+ )
968
+ self.decoder = CogVideoXDecoder3D(
969
+ in_channels=latent_channels,
970
+ out_channels=out_channels,
971
+ up_block_types=up_block_types,
972
+ block_out_channels=block_out_channels,
973
+ layers_per_block=layers_per_block,
974
+ act_fn=act_fn,
975
+ norm_eps=norm_eps,
976
+ norm_num_groups=norm_num_groups,
977
+ temporal_compression_ratio=temporal_compression_ratio,
978
+ )
979
+ self.quant_conv = CogVideoXSafeConv3d(2 * out_channels, 2 * out_channels, 1) if use_quant_conv else None
980
+ self.post_quant_conv = CogVideoXSafeConv3d(out_channels, out_channels, 1) if use_post_quant_conv else None
981
+
982
+ self.use_slicing = False
983
+ self.use_tiling = False
984
+
985
+ # Can be increased to decode more latent frames at once, but comes at a reasonable memory cost and it is not
986
+ # recommended because the temporal parts of the VAE, here, are tricky to understand.
987
+ # If you decode X latent frames together, the number of output frames is:
988
+ # (X + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) => X + 6 frames
989
+ #
990
+ # Example with num_latent_frames_batch_size = 2:
991
+ # - 12 latent frames: (0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11) are processed together
992
+ # => (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))
993
+ # => 6 * 8 = 48 frames
994
+ # - 13 latent frames: (0, 1, 2) (special case), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12) are processed together
995
+ # => (1 frame slice) * ((3 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale)) +
996
+ # ((13 - 3) // 2) * ((2 num_latent_frames_batch_size) + (2 conv cache) + (2 time upscale_1) + (4 time upscale_2) - (2 causal conv downscale))
997
+ # => 1 * 9 + 5 * 8 = 49 frames
998
+ # 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
999
+ # setting it to anything other than 2 would give poor results because the VAE hasn't been trained to be adaptive with different
1000
+ # number of temporal frames.
1001
+ self.num_latent_frames_batch_size = 2
1002
+
1003
+ # We make the minimum height and width of sample for tiling half that of the generally supported
1004
+ self.tile_sample_min_height = sample_height // 2
1005
+ self.tile_sample_min_width = sample_width // 2
1006
+ self.tile_latent_min_height = int(
1007
+ self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1))
1008
+ )
1009
+ self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1)))
1010
+
1011
+ # These are experimental overlap factors that were chosen based on experimentation and seem to work best for
1012
+ # 720x480 (WxH) resolution. The above resolution is the strongly recommended generation resolution in CogVideoX
1013
+ # and so the tiling implementation has only been tested on those specific resolutions.
1014
+ self.tile_overlap_factor_height = 1 / 6
1015
+ self.tile_overlap_factor_width = 1 / 5
1016
+
1017
+ def _set_gradient_checkpointing(self, module, value=False):
1018
+ if isinstance(module, (CogVideoXEncoder3D, CogVideoXDecoder3D)):
1019
+ module.gradient_checkpointing = value
1020
+
1021
+ def _clear_fake_context_parallel_cache(self):
1022
+ for name, module in self.named_modules():
1023
+ if isinstance(module, CogVideoXCausalConv3d):
1024
+ logger.debug(f"Clearing fake Context Parallel cache for layer: {name}")
1025
+ module._clear_fake_context_parallel_cache()
1026
+
1027
+ def enable_tiling(
1028
+ self,
1029
+ tile_sample_min_height: Optional[int] = None,
1030
+ tile_sample_min_width: Optional[int] = None,
1031
+ tile_overlap_factor_height: Optional[float] = None,
1032
+ tile_overlap_factor_width: Optional[float] = None,
1033
+ ) -> None:
1034
+ r"""
1035
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
1036
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
1037
+ processing larger images.
1038
+
1039
+ Args:
1040
+ tile_sample_min_height (`int`, *optional*):
1041
+ The minimum height required for a sample to be separated into tiles across the height dimension.
1042
+ tile_sample_min_width (`int`, *optional*):
1043
+ The minimum width required for a sample to be separated into tiles across the width dimension.
1044
+ tile_overlap_factor_height (`int`, *optional*):
1045
+ The minimum amount of overlap between two consecutive vertical tiles. This is to ensure that there are
1046
+ no tiling artifacts produced across the height dimension. Must be between 0 and 1. Setting a higher
1047
+ value might cause more tiles to be processed leading to slow down of the decoding process.
1048
+ tile_overlap_factor_width (`int`, *optional*):
1049
+ The minimum amount of overlap between two consecutive horizontal tiles. This is to ensure that there
1050
+ are no tiling artifacts produced across the width dimension. Must be between 0 and 1. Setting a higher
1051
+ value might cause more tiles to be processed leading to slow down of the decoding process.
1052
+ """
1053
+ self.use_tiling = True
1054
+ self.tile_sample_min_height = tile_sample_min_height or self.tile_sample_min_height
1055
+ self.tile_sample_min_width = tile_sample_min_width or self.tile_sample_min_width
1056
+ self.tile_latent_min_height = int(
1057
+ self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1))
1058
+ )
1059
+ self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1)))
1060
+ self.tile_overlap_factor_height = tile_overlap_factor_height or self.tile_overlap_factor_height
1061
+ self.tile_overlap_factor_width = tile_overlap_factor_width or self.tile_overlap_factor_width
1062
+
1063
+ def disable_tiling(self) -> None:
1064
+ r"""
1065
+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
1066
+ decoding in one step.
1067
+ """
1068
+ self.use_tiling = False
1069
+
1070
+ def enable_slicing(self) -> None:
1071
+ r"""
1072
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
1073
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
1074
+ """
1075
+ self.use_slicing = True
1076
+
1077
+ def disable_slicing(self) -> None:
1078
+ r"""
1079
+ Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
1080
+ decoding in one step.
1081
+ """
1082
+ self.use_slicing = False
1083
+
1084
+ @apply_forward_hook
1085
+ def encode(
1086
+ self, x: torch.Tensor, return_dict: bool = True
1087
+ ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
1088
+ """
1089
+ Encode a batch of images into latents.
1090
+
1091
+ Args:
1092
+ x (`torch.Tensor`): Input batch of images.
1093
+ return_dict (`bool`, *optional*, defaults to `True`):
1094
+ Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
1095
+
1096
+ Returns:
1097
+ The latent representations of the encoded images. If `return_dict` is True, a
1098
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
1099
+ """
1100
+ h = self.encoder(x)
1101
+ if self.quant_conv is not None:
1102
+ h = self.quant_conv(h)
1103
+ posterior = DiagonalGaussianDistribution(h)
1104
+ if not return_dict:
1105
+ return (posterior,)
1106
+ return AutoencoderKLOutput(latent_dist=posterior)
1107
+
1108
+ def _decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
1109
+ batch_size, num_channels, num_frames, height, width = z.shape
1110
+
1111
+ if self.use_tiling and (width > self.tile_latent_min_width or height > self.tile_latent_min_height):
1112
+ return self.tiled_decode(z, return_dict=return_dict)
1113
+
1114
+ frame_batch_size = self.num_latent_frames_batch_size
1115
+ dec = []
1116
+ for i in range(num_frames // frame_batch_size):
1117
+ remaining_frames = num_frames % frame_batch_size
1118
+ start_frame = frame_batch_size * i + (0 if i == 0 else remaining_frames)
1119
+ end_frame = frame_batch_size * (i + 1) + remaining_frames
1120
+ z_intermediate = z[:, :, start_frame:end_frame]
1121
+ if self.post_quant_conv is not None:
1122
+ z_intermediate = self.post_quant_conv(z_intermediate)
1123
+ z_intermediate = self.decoder(z_intermediate)
1124
+ dec.append(z_intermediate)
1125
+
1126
+ self._clear_fake_context_parallel_cache()
1127
+ dec = torch.cat(dec, dim=2)
1128
+
1129
+ if not return_dict:
1130
+ return (dec,)
1131
+
1132
+ return DecoderOutput(sample=dec)
1133
+
1134
+ @apply_forward_hook
1135
+ def decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
1136
+ """
1137
+ Decode a batch of images.
1138
+
1139
+ Args:
1140
+ z (`torch.Tensor`): Input batch of latent vectors.
1141
+ return_dict (`bool`, *optional*, defaults to `True`):
1142
+ Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
1143
+
1144
+ Returns:
1145
+ [`~models.vae.DecoderOutput`] or `tuple`:
1146
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
1147
+ returned.
1148
+ """
1149
+ if self.use_slicing and z.shape[0] > 1:
1150
+ decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
1151
+ decoded = torch.cat(decoded_slices)
1152
+ else:
1153
+ decoded = self._decode(z).sample
1154
+
1155
+ if not return_dict:
1156
+ return (decoded,)
1157
+ return DecoderOutput(sample=decoded)
1158
+
1159
+ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
1160
+ blend_extent = min(a.shape[3], b.shape[3], blend_extent)
1161
+ for y in range(blend_extent):
1162
+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (
1163
+ y / blend_extent
1164
+ )
1165
+ return b
1166
+
1167
+ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
1168
+ blend_extent = min(a.shape[4], b.shape[4], blend_extent)
1169
+ for x in range(blend_extent):
1170
+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (
1171
+ x / blend_extent
1172
+ )
1173
+ return b
1174
+
1175
+ def tiled_decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
1176
+ r"""
1177
+ Decode a batch of images using a tiled decoder.
1178
+
1179
+ Args:
1180
+ z (`torch.Tensor`): Input batch of latent vectors.
1181
+ return_dict (`bool`, *optional*, defaults to `True`):
1182
+ Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
1183
+
1184
+ Returns:
1185
+ [`~models.vae.DecoderOutput`] or `tuple`:
1186
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
1187
+ returned.
1188
+ """
1189
+ # Rough memory assessment:
1190
+ # - In CogVideoX-2B, there are a total of 24 CausalConv3d layers.
1191
+ # - The biggest intermediate dimensions are: [1, 128, 9, 480, 720].
1192
+ # - Assume fp16 (2 bytes per value).
1193
+ # Memory required: 1 * 128 * 9 * 480 * 720 * 24 * 2 / 1024**3 = 17.8 GB
1194
+ #
1195
+ # Memory assessment when using tiling:
1196
+ # - Assume everything as above but now HxW is 240x360 by tiling in half
1197
+ # Memory required: 1 * 128 * 9 * 240 * 360 * 24 * 2 / 1024**3 = 4.5 GB
1198
+
1199
+ batch_size, num_channels, num_frames, height, width = z.shape
1200
+
1201
+ overlap_height = int(self.tile_latent_min_height * (1 - self.tile_overlap_factor_height))
1202
+ overlap_width = int(self.tile_latent_min_width * (1 - self.tile_overlap_factor_width))
1203
+ blend_extent_height = int(self.tile_sample_min_height * self.tile_overlap_factor_height)
1204
+ blend_extent_width = int(self.tile_sample_min_width * self.tile_overlap_factor_width)
1205
+ row_limit_height = self.tile_sample_min_height - blend_extent_height
1206
+ row_limit_width = self.tile_sample_min_width - blend_extent_width
1207
+ frame_batch_size = self.num_latent_frames_batch_size
1208
+
1209
+ # Split z into overlapping tiles and decode them separately.
1210
+ # The tiles have an overlap to avoid seams between tiles.
1211
+ rows = []
1212
+ for i in range(0, height, overlap_height):
1213
+ row = []
1214
+ for j in range(0, width, overlap_width):
1215
+ time = []
1216
+ for k in range(num_frames // frame_batch_size):
1217
+ remaining_frames = num_frames % frame_batch_size
1218
+ start_frame = frame_batch_size * k + (0 if k == 0 else remaining_frames)
1219
+ end_frame = frame_batch_size * (k + 1) + remaining_frames
1220
+ tile = z[
1221
+ :,
1222
+ :,
1223
+ start_frame:end_frame,
1224
+ i : i + self.tile_latent_min_height,
1225
+ j : j + self.tile_latent_min_width,
1226
+ ]
1227
+ if self.post_quant_conv is not None:
1228
+ tile = self.post_quant_conv(tile)
1229
+ tile = self.decoder(tile)
1230
+ time.append(tile)
1231
+ self._clear_fake_context_parallel_cache()
1232
+ row.append(torch.cat(time, dim=2))
1233
+ rows.append(row)
1234
+
1235
+ result_rows = []
1236
+ for i, row in enumerate(rows):
1237
+ result_row = []
1238
+ for j, tile in enumerate(row):
1239
+ # blend the above tile and the left tile
1240
+ # to the current tile and add the current tile to the result row
1241
+ if i > 0:
1242
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent_height)
1243
+ if j > 0:
1244
+ tile = self.blend_h(row[j - 1], tile, blend_extent_width)
1245
+ result_row.append(tile[:, :, :, :row_limit_height, :row_limit_width])
1246
+ result_rows.append(torch.cat(result_row, dim=4))
1247
+
1248
+ dec = torch.cat(result_rows, dim=3)
1249
+
1250
+ if not return_dict:
1251
+ return (dec,)
1252
+
1253
+ return DecoderOutput(sample=dec)
1254
+
1255
+ def forward(
1256
+ self,
1257
+ sample: torch.Tensor,
1258
+ sample_posterior: bool = False,
1259
+ return_dict: bool = True,
1260
+ generator: Optional[torch.Generator] = None,
1261
+ ) -> Union[torch.Tensor, torch.Tensor]:
1262
+ x = sample
1263
+ posterior = self.encode(x).latent_dist
1264
+ if sample_posterior:
1265
+ z = posterior.sample(generator=generator)
1266
+ else:
1267
+ z = posterior.mode()
1268
+ dec = self.decode(z)
1269
+ if not return_dict:
1270
+ return (dec,)
1271
+ return dec