diffusers 0.30.2__py3-none-any.whl → 0.31.0__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 (173) hide show
  1. diffusers/__init__.py +38 -2
  2. diffusers/configuration_utils.py +12 -0
  3. diffusers/dependency_versions_table.py +1 -1
  4. diffusers/image_processor.py +257 -54
  5. diffusers/loaders/__init__.py +2 -0
  6. diffusers/loaders/ip_adapter.py +5 -1
  7. diffusers/loaders/lora_base.py +14 -7
  8. diffusers/loaders/lora_conversion_utils.py +332 -0
  9. diffusers/loaders/lora_pipeline.py +707 -41
  10. diffusers/loaders/peft.py +1 -0
  11. diffusers/loaders/single_file_utils.py +81 -4
  12. diffusers/loaders/textual_inversion.py +2 -0
  13. diffusers/loaders/unet.py +39 -8
  14. diffusers/models/__init__.py +4 -0
  15. diffusers/models/adapter.py +53 -53
  16. diffusers/models/attention.py +86 -10
  17. diffusers/models/attention_processor.py +169 -133
  18. diffusers/models/autoencoders/autoencoder_kl.py +71 -11
  19. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +287 -85
  20. diffusers/models/controlnet_flux.py +536 -0
  21. diffusers/models/controlnet_sd3.py +7 -3
  22. diffusers/models/controlnet_sparsectrl.py +0 -1
  23. diffusers/models/embeddings.py +238 -61
  24. diffusers/models/embeddings_flax.py +23 -9
  25. diffusers/models/model_loading_utils.py +182 -14
  26. diffusers/models/modeling_utils.py +283 -46
  27. diffusers/models/normalization.py +79 -0
  28. diffusers/models/transformers/__init__.py +1 -0
  29. diffusers/models/transformers/auraflow_transformer_2d.py +1 -0
  30. diffusers/models/transformers/cogvideox_transformer_3d.py +58 -36
  31. diffusers/models/transformers/pixart_transformer_2d.py +9 -1
  32. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  33. diffusers/models/transformers/transformer_flux.py +161 -44
  34. diffusers/models/transformers/transformer_sd3.py +7 -1
  35. diffusers/models/unets/unet_2d_condition.py +8 -8
  36. diffusers/models/unets/unet_motion_model.py +41 -63
  37. diffusers/models/upsampling.py +6 -6
  38. diffusers/pipelines/__init__.py +40 -7
  39. diffusers/pipelines/animatediff/__init__.py +2 -0
  40. diffusers/pipelines/animatediff/pipeline_animatediff.py +45 -21
  41. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +44 -20
  42. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +18 -4
  43. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +2 -0
  44. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +104 -66
  45. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  46. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +1 -1
  47. diffusers/pipelines/auto_pipeline.py +39 -8
  48. diffusers/pipelines/cogvideo/__init__.py +6 -0
  49. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +32 -34
  50. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +794 -0
  51. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +837 -0
  52. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +825 -0
  53. diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
  54. diffusers/pipelines/cogview3/__init__.py +47 -0
  55. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  56. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  57. diffusers/pipelines/controlnet/pipeline_controlnet.py +9 -1
  58. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +8 -0
  59. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +8 -0
  60. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +36 -13
  61. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +9 -1
  62. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +8 -1
  63. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +17 -3
  64. diffusers/pipelines/controlnet_sd3/__init__.py +4 -0
  65. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +3 -1
  66. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  67. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  68. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  69. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +16 -4
  70. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +1 -1
  71. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  72. diffusers/pipelines/flux/__init__.py +10 -0
  73. diffusers/pipelines/flux/pipeline_flux.py +53 -20
  74. diffusers/pipelines/flux/pipeline_flux_controlnet.py +984 -0
  75. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +988 -0
  76. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1182 -0
  77. diffusers/pipelines/flux/pipeline_flux_img2img.py +850 -0
  78. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1015 -0
  79. diffusers/pipelines/free_noise_utils.py +365 -5
  80. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +15 -3
  81. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +2 -2
  82. diffusers/pipelines/kolors/pipeline_kolors.py +1 -1
  83. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +14 -11
  84. diffusers/pipelines/kolors/tokenizer.py +4 -0
  85. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +1 -1
  86. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +1 -1
  87. diffusers/pipelines/latte/pipeline_latte.py +2 -2
  88. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +15 -3
  89. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +15 -3
  90. diffusers/pipelines/lumina/pipeline_lumina.py +2 -2
  91. diffusers/pipelines/pag/__init__.py +6 -0
  92. diffusers/pipelines/pag/pag_utils.py +8 -2
  93. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1 -1
  94. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1544 -0
  95. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +2 -2
  96. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1685 -0
  97. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +17 -5
  98. diffusers/pipelines/pag/pipeline_pag_kolors.py +1 -1
  99. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +1 -1
  100. diffusers/pipelines/pag/pipeline_pag_sd.py +18 -6
  101. diffusers/pipelines/pag/pipeline_pag_sd_3.py +12 -3
  102. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +5 -1
  103. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1091 -0
  104. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +18 -6
  105. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +31 -16
  106. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +42 -19
  107. diffusers/pipelines/pia/pipeline_pia.py +2 -0
  108. diffusers/pipelines/pipeline_loading_utils.py +225 -27
  109. diffusers/pipelines/pipeline_utils.py +123 -180
  110. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +1 -1
  111. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +1 -1
  112. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +35 -3
  113. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +2 -2
  114. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +28 -6
  115. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -1
  116. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +1 -1
  117. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +241 -81
  118. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +12 -3
  119. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +20 -4
  120. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +3 -3
  121. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  122. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +16 -4
  123. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +16 -4
  124. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -4
  125. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +29 -14
  126. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +29 -14
  127. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +1 -1
  128. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +1 -1
  129. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +16 -4
  130. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +15 -3
  131. diffusers/quantizers/__init__.py +16 -0
  132. diffusers/quantizers/auto.py +126 -0
  133. diffusers/quantizers/base.py +233 -0
  134. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  135. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +558 -0
  136. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  137. diffusers/quantizers/quantization_config.py +391 -0
  138. diffusers/schedulers/scheduling_ddim.py +4 -1
  139. diffusers/schedulers/scheduling_ddim_cogvideox.py +4 -1
  140. diffusers/schedulers/scheduling_ddim_parallel.py +4 -1
  141. diffusers/schedulers/scheduling_ddpm.py +4 -1
  142. diffusers/schedulers/scheduling_ddpm_parallel.py +4 -1
  143. diffusers/schedulers/scheduling_deis_multistep.py +78 -1
  144. diffusers/schedulers/scheduling_dpmsolver_multistep.py +82 -1
  145. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +80 -1
  146. diffusers/schedulers/scheduling_dpmsolver_sde.py +125 -10
  147. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +82 -1
  148. diffusers/schedulers/scheduling_edm_euler.py +8 -6
  149. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +4 -1
  150. diffusers/schedulers/scheduling_euler_discrete.py +92 -7
  151. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +4 -5
  152. diffusers/schedulers/scheduling_heun_discrete.py +114 -8
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +116 -11
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +110 -8
  155. diffusers/schedulers/scheduling_lms_discrete.py +76 -1
  156. diffusers/schedulers/scheduling_sasolver.py +78 -1
  157. diffusers/schedulers/scheduling_unclip.py +4 -1
  158. diffusers/schedulers/scheduling_unipc_multistep.py +78 -1
  159. diffusers/training_utils.py +48 -18
  160. diffusers/utils/__init__.py +2 -1
  161. diffusers/utils/dummy_pt_objects.py +60 -0
  162. diffusers/utils/dummy_torch_and_transformers_objects.py +195 -0
  163. diffusers/utils/hub_utils.py +16 -4
  164. diffusers/utils/import_utils.py +31 -8
  165. diffusers/utils/loading_utils.py +28 -4
  166. diffusers/utils/peft_utils.py +3 -3
  167. diffusers/utils/testing_utils.py +59 -0
  168. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/METADATA +7 -6
  169. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/RECORD +173 -147
  170. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/WHEEL +1 -1
  171. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/LICENSE +0 -0
  172. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/entry_points.txt +0 -0
  173. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,837 @@
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
+ import inspect
17
+ import math
18
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
19
+
20
+ import PIL
21
+ import torch
22
+ from transformers import T5EncoderModel, T5Tokenizer
23
+
24
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
25
+ from ...image_processor import PipelineImageInput
26
+ from ...loaders import CogVideoXLoraLoaderMixin
27
+ from ...models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
28
+ from ...models.embeddings import get_3d_rotary_pos_embed
29
+ from ...pipelines.pipeline_utils import DiffusionPipeline
30
+ from ...schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
31
+ from ...utils import (
32
+ logging,
33
+ replace_example_docstring,
34
+ )
35
+ from ...utils.torch_utils import randn_tensor
36
+ from ...video_processor import VideoProcessor
37
+ from .pipeline_output import CogVideoXPipelineOutput
38
+
39
+
40
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
41
+
42
+
43
+ EXAMPLE_DOC_STRING = """
44
+ Examples:
45
+ ```py
46
+ >>> import torch
47
+ >>> from diffusers import CogVideoXImageToVideoPipeline
48
+ >>> from diffusers.utils import export_to_video, load_image
49
+
50
+ >>> pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V", torch_dtype=torch.bfloat16)
51
+ >>> pipe.to("cuda")
52
+
53
+ >>> prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
54
+ >>> image = load_image(
55
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
56
+ ... )
57
+ >>> video = pipe(image, prompt, use_dynamic_cfg=True)
58
+ >>> export_to_video(video.frames[0], "output.mp4", fps=8)
59
+ ```
60
+ """
61
+
62
+
63
+ # Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid
64
+ def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
65
+ tw = tgt_width
66
+ th = tgt_height
67
+ h, w = src
68
+ r = h / w
69
+ if r > (th / tw):
70
+ resize_height = th
71
+ resize_width = int(round(th / h * w))
72
+ else:
73
+ resize_width = tw
74
+ resize_height = int(round(tw / w * h))
75
+
76
+ crop_top = int(round((th - resize_height) / 2.0))
77
+ crop_left = int(round((tw - resize_width) / 2.0))
78
+
79
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
80
+
81
+
82
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
83
+ def retrieve_timesteps(
84
+ scheduler,
85
+ num_inference_steps: Optional[int] = None,
86
+ device: Optional[Union[str, torch.device]] = None,
87
+ timesteps: Optional[List[int]] = None,
88
+ sigmas: Optional[List[float]] = None,
89
+ **kwargs,
90
+ ):
91
+ r"""
92
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
93
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
94
+
95
+ Args:
96
+ scheduler (`SchedulerMixin`):
97
+ The scheduler to get timesteps from.
98
+ num_inference_steps (`int`):
99
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
100
+ must be `None`.
101
+ device (`str` or `torch.device`, *optional*):
102
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
103
+ timesteps (`List[int]`, *optional*):
104
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
105
+ `num_inference_steps` and `sigmas` must be `None`.
106
+ sigmas (`List[float]`, *optional*):
107
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
108
+ `num_inference_steps` and `timesteps` must be `None`.
109
+
110
+ Returns:
111
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
112
+ second element is the number of inference steps.
113
+ """
114
+ if timesteps is not None and sigmas is not None:
115
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
116
+ if timesteps is not None:
117
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
118
+ if not accepts_timesteps:
119
+ raise ValueError(
120
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
121
+ f" timestep schedules. Please check whether you are using the correct scheduler."
122
+ )
123
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
124
+ timesteps = scheduler.timesteps
125
+ num_inference_steps = len(timesteps)
126
+ elif sigmas is not None:
127
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
128
+ if not accept_sigmas:
129
+ raise ValueError(
130
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
131
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
132
+ )
133
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
134
+ timesteps = scheduler.timesteps
135
+ num_inference_steps = len(timesteps)
136
+ else:
137
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
138
+ timesteps = scheduler.timesteps
139
+ return timesteps, num_inference_steps
140
+
141
+
142
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
143
+ def retrieve_latents(
144
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
145
+ ):
146
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
147
+ return encoder_output.latent_dist.sample(generator)
148
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
149
+ return encoder_output.latent_dist.mode()
150
+ elif hasattr(encoder_output, "latents"):
151
+ return encoder_output.latents
152
+ else:
153
+ raise AttributeError("Could not access latents of provided encoder_output")
154
+
155
+
156
+ class CogVideoXImageToVideoPipeline(DiffusionPipeline, CogVideoXLoraLoaderMixin):
157
+ r"""
158
+ Pipeline for image-to-video generation using CogVideoX.
159
+
160
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
161
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
162
+
163
+ Args:
164
+ vae ([`AutoencoderKL`]):
165
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
166
+ text_encoder ([`T5EncoderModel`]):
167
+ Frozen text-encoder. CogVideoX uses
168
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
169
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
170
+ tokenizer (`T5Tokenizer`):
171
+ Tokenizer of class
172
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
173
+ transformer ([`CogVideoXTransformer3DModel`]):
174
+ A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents.
175
+ scheduler ([`SchedulerMixin`]):
176
+ A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
177
+ """
178
+
179
+ _optional_components = []
180
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
181
+
182
+ _callback_tensor_inputs = [
183
+ "latents",
184
+ "prompt_embeds",
185
+ "negative_prompt_embeds",
186
+ ]
187
+
188
+ def __init__(
189
+ self,
190
+ tokenizer: T5Tokenizer,
191
+ text_encoder: T5EncoderModel,
192
+ vae: AutoencoderKLCogVideoX,
193
+ transformer: CogVideoXTransformer3DModel,
194
+ scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
195
+ ):
196
+ super().__init__()
197
+
198
+ self.register_modules(
199
+ tokenizer=tokenizer,
200
+ text_encoder=text_encoder,
201
+ vae=vae,
202
+ transformer=transformer,
203
+ scheduler=scheduler,
204
+ )
205
+ self.vae_scale_factor_spatial = (
206
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
207
+ )
208
+ self.vae_scale_factor_temporal = (
209
+ self.vae.config.temporal_compression_ratio if hasattr(self, "vae") and self.vae is not None else 4
210
+ )
211
+ self.vae_scaling_factor_image = (
212
+ self.vae.config.scaling_factor if hasattr(self, "vae") and self.vae is not None else 0.7
213
+ )
214
+
215
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
216
+
217
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._get_t5_prompt_embeds
218
+ def _get_t5_prompt_embeds(
219
+ self,
220
+ prompt: Union[str, List[str]] = None,
221
+ num_videos_per_prompt: int = 1,
222
+ max_sequence_length: int = 226,
223
+ device: Optional[torch.device] = None,
224
+ dtype: Optional[torch.dtype] = None,
225
+ ):
226
+ device = device or self._execution_device
227
+ dtype = dtype or self.text_encoder.dtype
228
+
229
+ prompt = [prompt] if isinstance(prompt, str) else prompt
230
+ batch_size = len(prompt)
231
+
232
+ text_inputs = self.tokenizer(
233
+ prompt,
234
+ padding="max_length",
235
+ max_length=max_sequence_length,
236
+ truncation=True,
237
+ add_special_tokens=True,
238
+ return_tensors="pt",
239
+ )
240
+ text_input_ids = text_inputs.input_ids
241
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
242
+
243
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
244
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
245
+ logger.warning(
246
+ "The following part of your input was truncated because `max_sequence_length` is set to "
247
+ f" {max_sequence_length} tokens: {removed_text}"
248
+ )
249
+
250
+ prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
251
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
252
+
253
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
254
+ _, seq_len, _ = prompt_embeds.shape
255
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
256
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
257
+
258
+ return prompt_embeds
259
+
260
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.encode_prompt
261
+ def encode_prompt(
262
+ self,
263
+ prompt: Union[str, List[str]],
264
+ negative_prompt: Optional[Union[str, List[str]]] = None,
265
+ do_classifier_free_guidance: bool = True,
266
+ num_videos_per_prompt: int = 1,
267
+ prompt_embeds: Optional[torch.Tensor] = None,
268
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
269
+ max_sequence_length: int = 226,
270
+ device: Optional[torch.device] = None,
271
+ dtype: Optional[torch.dtype] = None,
272
+ ):
273
+ r"""
274
+ Encodes the prompt into text encoder hidden states.
275
+
276
+ Args:
277
+ prompt (`str` or `List[str]`, *optional*):
278
+ prompt to be encoded
279
+ negative_prompt (`str` or `List[str]`, *optional*):
280
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
281
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
282
+ less than `1`).
283
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
284
+ Whether to use classifier free guidance or not.
285
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
286
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
287
+ prompt_embeds (`torch.Tensor`, *optional*):
288
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
289
+ provided, text embeddings will be generated from `prompt` input argument.
290
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
291
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
292
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
293
+ argument.
294
+ device: (`torch.device`, *optional*):
295
+ torch device
296
+ dtype: (`torch.dtype`, *optional*):
297
+ torch dtype
298
+ """
299
+ device = device or self._execution_device
300
+
301
+ prompt = [prompt] if isinstance(prompt, str) else prompt
302
+ if prompt is not None:
303
+ batch_size = len(prompt)
304
+ else:
305
+ batch_size = prompt_embeds.shape[0]
306
+
307
+ if prompt_embeds is None:
308
+ prompt_embeds = self._get_t5_prompt_embeds(
309
+ prompt=prompt,
310
+ num_videos_per_prompt=num_videos_per_prompt,
311
+ max_sequence_length=max_sequence_length,
312
+ device=device,
313
+ dtype=dtype,
314
+ )
315
+
316
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
317
+ negative_prompt = negative_prompt or ""
318
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
319
+
320
+ if prompt is not None and type(prompt) is not type(negative_prompt):
321
+ raise TypeError(
322
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
323
+ f" {type(prompt)}."
324
+ )
325
+ elif batch_size != len(negative_prompt):
326
+ raise ValueError(
327
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
328
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
329
+ " the batch size of `prompt`."
330
+ )
331
+
332
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
333
+ prompt=negative_prompt,
334
+ num_videos_per_prompt=num_videos_per_prompt,
335
+ max_sequence_length=max_sequence_length,
336
+ device=device,
337
+ dtype=dtype,
338
+ )
339
+
340
+ return prompt_embeds, negative_prompt_embeds
341
+
342
+ def prepare_latents(
343
+ self,
344
+ image: torch.Tensor,
345
+ batch_size: int = 1,
346
+ num_channels_latents: int = 16,
347
+ num_frames: int = 13,
348
+ height: int = 60,
349
+ width: int = 90,
350
+ dtype: Optional[torch.dtype] = None,
351
+ device: Optional[torch.device] = None,
352
+ generator: Optional[torch.Generator] = None,
353
+ latents: Optional[torch.Tensor] = None,
354
+ ):
355
+ if isinstance(generator, list) and len(generator) != batch_size:
356
+ raise ValueError(
357
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
358
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
359
+ )
360
+
361
+ num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
362
+ shape = (
363
+ batch_size,
364
+ num_frames,
365
+ num_channels_latents,
366
+ height // self.vae_scale_factor_spatial,
367
+ width // self.vae_scale_factor_spatial,
368
+ )
369
+
370
+ image = image.unsqueeze(2) # [B, C, F, H, W]
371
+
372
+ if isinstance(generator, list):
373
+ image_latents = [
374
+ retrieve_latents(self.vae.encode(image[i].unsqueeze(0)), generator[i]) for i in range(batch_size)
375
+ ]
376
+ else:
377
+ image_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator) for img in image]
378
+
379
+ image_latents = torch.cat(image_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W]
380
+ image_latents = self.vae_scaling_factor_image * image_latents
381
+
382
+ padding_shape = (
383
+ batch_size,
384
+ num_frames - 1,
385
+ num_channels_latents,
386
+ height // self.vae_scale_factor_spatial,
387
+ width // self.vae_scale_factor_spatial,
388
+ )
389
+ latent_padding = torch.zeros(padding_shape, device=device, dtype=dtype)
390
+ image_latents = torch.cat([image_latents, latent_padding], dim=1)
391
+
392
+ if latents is None:
393
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
394
+ else:
395
+ latents = latents.to(device)
396
+
397
+ # scale the initial noise by the standard deviation required by the scheduler
398
+ latents = latents * self.scheduler.init_noise_sigma
399
+ return latents, image_latents
400
+
401
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.decode_latents
402
+ def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
403
+ latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width]
404
+ latents = 1 / self.vae_scaling_factor_image * latents
405
+
406
+ frames = self.vae.decode(latents).sample
407
+ return frames
408
+
409
+ # Copied from diffusers.pipelines.animatediff.pipeline_animatediff_video2video.AnimateDiffVideoToVideoPipeline.get_timesteps
410
+ def get_timesteps(self, num_inference_steps, timesteps, strength, device):
411
+ # get the original timestep using init_timestep
412
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
413
+
414
+ t_start = max(num_inference_steps - init_timestep, 0)
415
+ timesteps = timesteps[t_start * self.scheduler.order :]
416
+
417
+ return timesteps, num_inference_steps - t_start
418
+
419
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
420
+ def prepare_extra_step_kwargs(self, generator, eta):
421
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
422
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
423
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
424
+ # and should be between [0, 1]
425
+
426
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
427
+ extra_step_kwargs = {}
428
+ if accepts_eta:
429
+ extra_step_kwargs["eta"] = eta
430
+
431
+ # check if the scheduler accepts generator
432
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
433
+ if accepts_generator:
434
+ extra_step_kwargs["generator"] = generator
435
+ return extra_step_kwargs
436
+
437
+ def check_inputs(
438
+ self,
439
+ image,
440
+ prompt,
441
+ height,
442
+ width,
443
+ negative_prompt,
444
+ callback_on_step_end_tensor_inputs,
445
+ latents=None,
446
+ prompt_embeds=None,
447
+ negative_prompt_embeds=None,
448
+ ):
449
+ if (
450
+ not isinstance(image, torch.Tensor)
451
+ and not isinstance(image, PIL.Image.Image)
452
+ and not isinstance(image, list)
453
+ ):
454
+ raise ValueError(
455
+ "`image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
456
+ f" {type(image)}"
457
+ )
458
+
459
+ if height % 8 != 0 or width % 8 != 0:
460
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
461
+
462
+ if callback_on_step_end_tensor_inputs is not None and not all(
463
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
464
+ ):
465
+ raise ValueError(
466
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
467
+ )
468
+ if prompt is not None and prompt_embeds is not None:
469
+ raise ValueError(
470
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
471
+ " only forward one of the two."
472
+ )
473
+ elif prompt is None and prompt_embeds is None:
474
+ raise ValueError(
475
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
476
+ )
477
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
478
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
479
+
480
+ if prompt is not None and negative_prompt_embeds is not None:
481
+ raise ValueError(
482
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
483
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
484
+ )
485
+
486
+ if negative_prompt is not None and negative_prompt_embeds is not None:
487
+ raise ValueError(
488
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
489
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
490
+ )
491
+
492
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
493
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
494
+ raise ValueError(
495
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
496
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
497
+ f" {negative_prompt_embeds.shape}."
498
+ )
499
+
500
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.fuse_qkv_projections
501
+ def fuse_qkv_projections(self) -> None:
502
+ r"""Enables fused QKV projections."""
503
+ self.fusing_transformer = True
504
+ self.transformer.fuse_qkv_projections()
505
+
506
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.unfuse_qkv_projections
507
+ def unfuse_qkv_projections(self) -> None:
508
+ r"""Disable QKV projection fusion if enabled."""
509
+ if not self.fusing_transformer:
510
+ logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.")
511
+ else:
512
+ self.transformer.unfuse_qkv_projections()
513
+ self.fusing_transformer = False
514
+
515
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._prepare_rotary_positional_embeddings
516
+ def _prepare_rotary_positional_embeddings(
517
+ self,
518
+ height: int,
519
+ width: int,
520
+ num_frames: int,
521
+ device: torch.device,
522
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
523
+ grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
524
+ grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
525
+ base_size_width = 720 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
526
+ base_size_height = 480 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
527
+
528
+ grid_crops_coords = get_resize_crop_region_for_grid(
529
+ (grid_height, grid_width), base_size_width, base_size_height
530
+ )
531
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
532
+ embed_dim=self.transformer.config.attention_head_dim,
533
+ crops_coords=grid_crops_coords,
534
+ grid_size=(grid_height, grid_width),
535
+ temporal_size=num_frames,
536
+ )
537
+
538
+ freqs_cos = freqs_cos.to(device=device)
539
+ freqs_sin = freqs_sin.to(device=device)
540
+ return freqs_cos, freqs_sin
541
+
542
+ @property
543
+ def guidance_scale(self):
544
+ return self._guidance_scale
545
+
546
+ @property
547
+ def num_timesteps(self):
548
+ return self._num_timesteps
549
+
550
+ @property
551
+ def attention_kwargs(self):
552
+ return self._attention_kwargs
553
+
554
+ @property
555
+ def interrupt(self):
556
+ return self._interrupt
557
+
558
+ @torch.no_grad()
559
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
560
+ def __call__(
561
+ self,
562
+ image: PipelineImageInput,
563
+ prompt: Optional[Union[str, List[str]]] = None,
564
+ negative_prompt: Optional[Union[str, List[str]]] = None,
565
+ height: int = 480,
566
+ width: int = 720,
567
+ num_frames: int = 49,
568
+ num_inference_steps: int = 50,
569
+ timesteps: Optional[List[int]] = None,
570
+ guidance_scale: float = 6,
571
+ use_dynamic_cfg: bool = False,
572
+ num_videos_per_prompt: int = 1,
573
+ eta: float = 0.0,
574
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
575
+ latents: Optional[torch.FloatTensor] = None,
576
+ prompt_embeds: Optional[torch.FloatTensor] = None,
577
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
578
+ output_type: str = "pil",
579
+ return_dict: bool = True,
580
+ attention_kwargs: Optional[Dict[str, Any]] = None,
581
+ callback_on_step_end: Optional[
582
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
583
+ ] = None,
584
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
585
+ max_sequence_length: int = 226,
586
+ ) -> Union[CogVideoXPipelineOutput, Tuple]:
587
+ """
588
+ Function invoked when calling the pipeline for generation.
589
+
590
+ Args:
591
+ image (`PipelineImageInput`):
592
+ The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
593
+ prompt (`str` or `List[str]`, *optional*):
594
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
595
+ instead.
596
+ negative_prompt (`str` or `List[str]`, *optional*):
597
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
598
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
599
+ less than `1`).
600
+ height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
601
+ The height in pixels of the generated image. This is set to 480 by default for the best results.
602
+ width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
603
+ The width in pixels of the generated image. This is set to 720 by default for the best results.
604
+ num_frames (`int`, defaults to `48`):
605
+ Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
606
+ contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where
607
+ num_seconds is 6 and fps is 8. However, since videos can be saved at any fps, the only condition that
608
+ needs to be satisfied is that of divisibility mentioned above.
609
+ num_inference_steps (`int`, *optional*, defaults to 50):
610
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
611
+ expense of slower inference.
612
+ timesteps (`List[int]`, *optional*):
613
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
614
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
615
+ passed will be used. Must be in descending order.
616
+ guidance_scale (`float`, *optional*, defaults to 7.0):
617
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
618
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
619
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
620
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
621
+ usually at the expense of lower image quality.
622
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
623
+ The number of videos to generate per prompt.
624
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
625
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
626
+ to make generation deterministic.
627
+ latents (`torch.FloatTensor`, *optional*):
628
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
629
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
630
+ tensor will ge generated by sampling using the supplied random `generator`.
631
+ prompt_embeds (`torch.FloatTensor`, *optional*):
632
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
633
+ provided, text embeddings will be generated from `prompt` input argument.
634
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
635
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
636
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
637
+ argument.
638
+ output_type (`str`, *optional*, defaults to `"pil"`):
639
+ The output format of the generate image. Choose between
640
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
641
+ return_dict (`bool`, *optional*, defaults to `True`):
642
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
643
+ of a plain tuple.
644
+ attention_kwargs (`dict`, *optional*):
645
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
646
+ `self.processor` in
647
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
648
+ callback_on_step_end (`Callable`, *optional*):
649
+ A function that calls at the end of each denoising steps during the inference. The function is called
650
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
651
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
652
+ `callback_on_step_end_tensor_inputs`.
653
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
654
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
655
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
656
+ `._callback_tensor_inputs` attribute of your pipeline class.
657
+ max_sequence_length (`int`, defaults to `226`):
658
+ Maximum sequence length in encoded prompt. Must be consistent with
659
+ `self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
660
+
661
+ Examples:
662
+
663
+ Returns:
664
+ [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] or `tuple`:
665
+ [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
666
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
667
+ """
668
+
669
+ if num_frames > 49:
670
+ raise ValueError(
671
+ "The number of frames must be less than 49 for now due to static positional embeddings. This will be updated in the future to remove this limitation."
672
+ )
673
+
674
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
675
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
676
+
677
+ num_videos_per_prompt = 1
678
+
679
+ # 1. Check inputs. Raise error if not correct
680
+ self.check_inputs(
681
+ image=image,
682
+ prompt=prompt,
683
+ height=height,
684
+ width=width,
685
+ negative_prompt=negative_prompt,
686
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
687
+ latents=latents,
688
+ prompt_embeds=prompt_embeds,
689
+ negative_prompt_embeds=negative_prompt_embeds,
690
+ )
691
+ self._guidance_scale = guidance_scale
692
+ self._attention_kwargs = attention_kwargs
693
+ self._interrupt = False
694
+
695
+ # 2. Default call parameters
696
+ if prompt is not None and isinstance(prompt, str):
697
+ batch_size = 1
698
+ elif prompt is not None and isinstance(prompt, list):
699
+ batch_size = len(prompt)
700
+ else:
701
+ batch_size = prompt_embeds.shape[0]
702
+
703
+ device = self._execution_device
704
+
705
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
706
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
707
+ # corresponds to doing no classifier free guidance.
708
+ do_classifier_free_guidance = guidance_scale > 1.0
709
+
710
+ # 3. Encode input prompt
711
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
712
+ prompt=prompt,
713
+ negative_prompt=negative_prompt,
714
+ do_classifier_free_guidance=do_classifier_free_guidance,
715
+ num_videos_per_prompt=num_videos_per_prompt,
716
+ prompt_embeds=prompt_embeds,
717
+ negative_prompt_embeds=negative_prompt_embeds,
718
+ max_sequence_length=max_sequence_length,
719
+ device=device,
720
+ )
721
+ if do_classifier_free_guidance:
722
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
723
+
724
+ # 4. Prepare timesteps
725
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
726
+ self._num_timesteps = len(timesteps)
727
+
728
+ # 5. Prepare latents
729
+ image = self.video_processor.preprocess(image, height=height, width=width).to(
730
+ device, dtype=prompt_embeds.dtype
731
+ )
732
+
733
+ latent_channels = self.transformer.config.in_channels // 2
734
+ latents, image_latents = self.prepare_latents(
735
+ image,
736
+ batch_size * num_videos_per_prompt,
737
+ latent_channels,
738
+ num_frames,
739
+ height,
740
+ width,
741
+ prompt_embeds.dtype,
742
+ device,
743
+ generator,
744
+ latents,
745
+ )
746
+
747
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
748
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
749
+
750
+ # 7. Create rotary embeds if required
751
+ image_rotary_emb = (
752
+ self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device)
753
+ if self.transformer.config.use_rotary_positional_embeddings
754
+ else None
755
+ )
756
+
757
+ # 8. Denoising loop
758
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
759
+
760
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
761
+ # for DPM-solver++
762
+ old_pred_original_sample = None
763
+ for i, t in enumerate(timesteps):
764
+ if self.interrupt:
765
+ continue
766
+
767
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
768
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
769
+
770
+ latent_image_input = torch.cat([image_latents] * 2) if do_classifier_free_guidance else image_latents
771
+ latent_model_input = torch.cat([latent_model_input, latent_image_input], dim=2)
772
+
773
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
774
+ timestep = t.expand(latent_model_input.shape[0])
775
+
776
+ # predict noise model_output
777
+ noise_pred = self.transformer(
778
+ hidden_states=latent_model_input,
779
+ encoder_hidden_states=prompt_embeds,
780
+ timestep=timestep,
781
+ image_rotary_emb=image_rotary_emb,
782
+ attention_kwargs=attention_kwargs,
783
+ return_dict=False,
784
+ )[0]
785
+ noise_pred = noise_pred.float()
786
+
787
+ # perform guidance
788
+ if use_dynamic_cfg:
789
+ self._guidance_scale = 1 + guidance_scale * (
790
+ (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
791
+ )
792
+ if do_classifier_free_guidance:
793
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
794
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
795
+
796
+ # compute the previous noisy sample x_t -> x_t-1
797
+ if not isinstance(self.scheduler, CogVideoXDPMScheduler):
798
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
799
+ else:
800
+ latents, old_pred_original_sample = self.scheduler.step(
801
+ noise_pred,
802
+ old_pred_original_sample,
803
+ t,
804
+ timesteps[i - 1] if i > 0 else None,
805
+ latents,
806
+ **extra_step_kwargs,
807
+ return_dict=False,
808
+ )
809
+ latents = latents.to(prompt_embeds.dtype)
810
+
811
+ # call the callback, if provided
812
+ if callback_on_step_end is not None:
813
+ callback_kwargs = {}
814
+ for k in callback_on_step_end_tensor_inputs:
815
+ callback_kwargs[k] = locals()[k]
816
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
817
+
818
+ latents = callback_outputs.pop("latents", latents)
819
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
820
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
821
+
822
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
823
+ progress_bar.update()
824
+
825
+ if not output_type == "latent":
826
+ video = self.decode_latents(latents)
827
+ video = self.video_processor.postprocess_video(video=video, output_type=output_type)
828
+ else:
829
+ video = latents
830
+
831
+ # Offload all models
832
+ self.maybe_free_model_hooks()
833
+
834
+ if not return_dict:
835
+ return (video,)
836
+
837
+ return CogVideoXPipelineOutput(frames=video)