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,746 @@
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 dataclasses import dataclass
19
+ from typing import Callable, Dict, List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ from transformers import T5EncoderModel, T5Tokenizer
23
+
24
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
25
+ from ...models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
26
+ from ...models.embeddings import get_3d_rotary_pos_embed
27
+ from ...pipelines.pipeline_utils import DiffusionPipeline
28
+ from ...schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
29
+ from ...utils import BaseOutput, logging, replace_example_docstring
30
+ from ...utils.torch_utils import randn_tensor
31
+ from ...video_processor import VideoProcessor
32
+
33
+
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+
37
+ EXAMPLE_DOC_STRING = """
38
+ Examples:
39
+ ```python
40
+ >>> import torch
41
+ >>> from diffusers import CogVideoXPipeline
42
+ >>> from diffusers.utils import export_to_video
43
+
44
+ >>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
45
+ >>> pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16).to("cuda")
46
+ >>> prompt = (
47
+ ... "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
48
+ ... "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
49
+ ... "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
50
+ ... "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
51
+ ... "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
52
+ ... "atmosphere of this unique musical performance."
53
+ ... )
54
+ >>> video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
55
+ >>> export_to_video(video, "output.mp4", fps=8)
56
+ ```
57
+ """
58
+
59
+
60
+ # Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid
61
+ def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
62
+ tw = tgt_width
63
+ th = tgt_height
64
+ h, w = src
65
+ r = h / w
66
+ if r > (th / tw):
67
+ resize_height = th
68
+ resize_width = int(round(th / h * w))
69
+ else:
70
+ resize_width = tw
71
+ resize_height = int(round(tw / w * h))
72
+
73
+ crop_top = int(round((th - resize_height) / 2.0))
74
+ crop_left = int(round((tw - resize_width) / 2.0))
75
+
76
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
77
+
78
+
79
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
80
+ def retrieve_timesteps(
81
+ scheduler,
82
+ num_inference_steps: Optional[int] = None,
83
+ device: Optional[Union[str, torch.device]] = None,
84
+ timesteps: Optional[List[int]] = None,
85
+ sigmas: Optional[List[float]] = None,
86
+ **kwargs,
87
+ ):
88
+ """
89
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
90
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
91
+
92
+ Args:
93
+ scheduler (`SchedulerMixin`):
94
+ The scheduler to get timesteps from.
95
+ num_inference_steps (`int`):
96
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
97
+ must be `None`.
98
+ device (`str` or `torch.device`, *optional*):
99
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
100
+ timesteps (`List[int]`, *optional*):
101
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
102
+ `num_inference_steps` and `sigmas` must be `None`.
103
+ sigmas (`List[float]`, *optional*):
104
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
105
+ `num_inference_steps` and `timesteps` must be `None`.
106
+
107
+ Returns:
108
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
109
+ second element is the number of inference steps.
110
+ """
111
+ if timesteps is not None and sigmas is not None:
112
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
113
+ if timesteps is not None:
114
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
115
+ if not accepts_timesteps:
116
+ raise ValueError(
117
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
118
+ f" timestep schedules. Please check whether you are using the correct scheduler."
119
+ )
120
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
121
+ timesteps = scheduler.timesteps
122
+ num_inference_steps = len(timesteps)
123
+ elif sigmas is not None:
124
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
125
+ if not accept_sigmas:
126
+ raise ValueError(
127
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
128
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
129
+ )
130
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
131
+ timesteps = scheduler.timesteps
132
+ num_inference_steps = len(timesteps)
133
+ else:
134
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
135
+ timesteps = scheduler.timesteps
136
+ return timesteps, num_inference_steps
137
+
138
+
139
+ @dataclass
140
+ class CogVideoXPipelineOutput(BaseOutput):
141
+ r"""
142
+ Output class for CogVideo pipelines.
143
+
144
+ Args:
145
+ frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]):
146
+ List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing
147
+ denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape
148
+ `(batch_size, num_frames, channels, height, width)`.
149
+ """
150
+
151
+ frames: torch.Tensor
152
+
153
+
154
+ class CogVideoXPipeline(DiffusionPipeline):
155
+ r"""
156
+ Pipeline for text-to-video generation using CogVideoX.
157
+
158
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
159
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
160
+
161
+ Args:
162
+ vae ([`AutoencoderKL`]):
163
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
164
+ text_encoder ([`T5EncoderModel`]):
165
+ Frozen text-encoder. CogVideoX uses
166
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
167
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
168
+ tokenizer (`T5Tokenizer`):
169
+ Tokenizer of class
170
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
171
+ transformer ([`CogVideoXTransformer3DModel`]):
172
+ A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents.
173
+ scheduler ([`SchedulerMixin`]):
174
+ A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
175
+ """
176
+
177
+ _optional_components = []
178
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
179
+
180
+ _callback_tensor_inputs = [
181
+ "latents",
182
+ "prompt_embeds",
183
+ "negative_prompt_embeds",
184
+ ]
185
+
186
+ def __init__(
187
+ self,
188
+ tokenizer: T5Tokenizer,
189
+ text_encoder: T5EncoderModel,
190
+ vae: AutoencoderKLCogVideoX,
191
+ transformer: CogVideoXTransformer3DModel,
192
+ scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
193
+ ):
194
+ super().__init__()
195
+
196
+ self.register_modules(
197
+ tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler
198
+ )
199
+ self.vae_scale_factor_spatial = (
200
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
201
+ )
202
+ self.vae_scale_factor_temporal = (
203
+ self.vae.config.temporal_compression_ratio if hasattr(self, "vae") and self.vae is not None else 4
204
+ )
205
+
206
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
207
+
208
+ def _get_t5_prompt_embeds(
209
+ self,
210
+ prompt: Union[str, List[str]] = None,
211
+ num_videos_per_prompt: int = 1,
212
+ max_sequence_length: int = 226,
213
+ device: Optional[torch.device] = None,
214
+ dtype: Optional[torch.dtype] = None,
215
+ ):
216
+ device = device or self._execution_device
217
+ dtype = dtype or self.text_encoder.dtype
218
+
219
+ prompt = [prompt] if isinstance(prompt, str) else prompt
220
+ batch_size = len(prompt)
221
+
222
+ text_inputs = self.tokenizer(
223
+ prompt,
224
+ padding="max_length",
225
+ max_length=max_sequence_length,
226
+ truncation=True,
227
+ add_special_tokens=True,
228
+ return_tensors="pt",
229
+ )
230
+ text_input_ids = text_inputs.input_ids
231
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
232
+
233
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
234
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
235
+ logger.warning(
236
+ "The following part of your input was truncated because `max_sequence_length` is set to "
237
+ f" {max_sequence_length} tokens: {removed_text}"
238
+ )
239
+
240
+ prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
241
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
242
+
243
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
244
+ _, seq_len, _ = prompt_embeds.shape
245
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
246
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
247
+
248
+ return prompt_embeds
249
+
250
+ def encode_prompt(
251
+ self,
252
+ prompt: Union[str, List[str]],
253
+ negative_prompt: Optional[Union[str, List[str]]] = None,
254
+ do_classifier_free_guidance: bool = True,
255
+ num_videos_per_prompt: int = 1,
256
+ prompt_embeds: Optional[torch.Tensor] = None,
257
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
258
+ max_sequence_length: int = 226,
259
+ device: Optional[torch.device] = None,
260
+ dtype: Optional[torch.dtype] = None,
261
+ ):
262
+ r"""
263
+ Encodes the prompt into text encoder hidden states.
264
+
265
+ Args:
266
+ prompt (`str` or `List[str]`, *optional*):
267
+ prompt to be encoded
268
+ negative_prompt (`str` or `List[str]`, *optional*):
269
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
270
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
271
+ less than `1`).
272
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
273
+ Whether to use classifier free guidance or not.
274
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
275
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
276
+ prompt_embeds (`torch.Tensor`, *optional*):
277
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
278
+ provided, text embeddings will be generated from `prompt` input argument.
279
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
280
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
281
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
282
+ argument.
283
+ device: (`torch.device`, *optional*):
284
+ torch device
285
+ dtype: (`torch.dtype`, *optional*):
286
+ torch dtype
287
+ """
288
+ device = device or self._execution_device
289
+
290
+ prompt = [prompt] if isinstance(prompt, str) else prompt
291
+ if prompt is not None:
292
+ batch_size = len(prompt)
293
+ else:
294
+ batch_size = prompt_embeds.shape[0]
295
+
296
+ if prompt_embeds is None:
297
+ prompt_embeds = self._get_t5_prompt_embeds(
298
+ prompt=prompt,
299
+ num_videos_per_prompt=num_videos_per_prompt,
300
+ max_sequence_length=max_sequence_length,
301
+ device=device,
302
+ dtype=dtype,
303
+ )
304
+
305
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
306
+ negative_prompt = negative_prompt or ""
307
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
308
+
309
+ if prompt is not None and type(prompt) is not type(negative_prompt):
310
+ raise TypeError(
311
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
312
+ f" {type(prompt)}."
313
+ )
314
+ elif batch_size != len(negative_prompt):
315
+ raise ValueError(
316
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
317
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
318
+ " the batch size of `prompt`."
319
+ )
320
+
321
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
322
+ prompt=negative_prompt,
323
+ num_videos_per_prompt=num_videos_per_prompt,
324
+ max_sequence_length=max_sequence_length,
325
+ device=device,
326
+ dtype=dtype,
327
+ )
328
+
329
+ return prompt_embeds, negative_prompt_embeds
330
+
331
+ def prepare_latents(
332
+ self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
333
+ ):
334
+ shape = (
335
+ batch_size,
336
+ (num_frames - 1) // self.vae_scale_factor_temporal + 1,
337
+ num_channels_latents,
338
+ height // self.vae_scale_factor_spatial,
339
+ width // self.vae_scale_factor_spatial,
340
+ )
341
+ if isinstance(generator, list) and len(generator) != batch_size:
342
+ raise ValueError(
343
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
344
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
345
+ )
346
+
347
+ if latents is None:
348
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
349
+ else:
350
+ latents = latents.to(device)
351
+
352
+ # scale the initial noise by the standard deviation required by the scheduler
353
+ latents = latents * self.scheduler.init_noise_sigma
354
+ return latents
355
+
356
+ def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
357
+ latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width]
358
+ latents = 1 / self.vae.config.scaling_factor * latents
359
+
360
+ frames = self.vae.decode(latents).sample
361
+ return frames
362
+
363
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
364
+ def prepare_extra_step_kwargs(self, generator, eta):
365
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
366
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
367
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
368
+ # and should be between [0, 1]
369
+
370
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
371
+ extra_step_kwargs = {}
372
+ if accepts_eta:
373
+ extra_step_kwargs["eta"] = eta
374
+
375
+ # check if the scheduler accepts generator
376
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
377
+ if accepts_generator:
378
+ extra_step_kwargs["generator"] = generator
379
+ return extra_step_kwargs
380
+
381
+ # Copied from diffusers.pipelines.latte.pipeline_latte.LattePipeline.check_inputs
382
+ def check_inputs(
383
+ self,
384
+ prompt,
385
+ height,
386
+ width,
387
+ negative_prompt,
388
+ callback_on_step_end_tensor_inputs,
389
+ prompt_embeds=None,
390
+ negative_prompt_embeds=None,
391
+ ):
392
+ if height % 8 != 0 or width % 8 != 0:
393
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
394
+
395
+ if callback_on_step_end_tensor_inputs is not None and not all(
396
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
397
+ ):
398
+ raise ValueError(
399
+ 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]}"
400
+ )
401
+ if prompt is not None and prompt_embeds is not None:
402
+ raise ValueError(
403
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
404
+ " only forward one of the two."
405
+ )
406
+ elif prompt is None and prompt_embeds is None:
407
+ raise ValueError(
408
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
409
+ )
410
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
411
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
412
+
413
+ if prompt is not None and negative_prompt_embeds is not None:
414
+ raise ValueError(
415
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
416
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
417
+ )
418
+
419
+ if negative_prompt is not None and negative_prompt_embeds is not None:
420
+ raise ValueError(
421
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
422
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
423
+ )
424
+
425
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
426
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
427
+ raise ValueError(
428
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
429
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
430
+ f" {negative_prompt_embeds.shape}."
431
+ )
432
+
433
+ def fuse_qkv_projections(self) -> None:
434
+ r"""Enables fused QKV projections."""
435
+ self.fusing_transformer = True
436
+ self.transformer.fuse_qkv_projections()
437
+
438
+ def unfuse_qkv_projections(self) -> None:
439
+ r"""Disable QKV projection fusion if enabled."""
440
+ if not self.fusing_transformer:
441
+ logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.")
442
+ else:
443
+ self.transformer.unfuse_qkv_projections()
444
+ self.fusing_transformer = False
445
+
446
+ def _prepare_rotary_positional_embeddings(
447
+ self,
448
+ height: int,
449
+ width: int,
450
+ num_frames: int,
451
+ device: torch.device,
452
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
453
+ grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
454
+ grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
455
+ base_size_width = 720 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
456
+ base_size_height = 480 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
457
+
458
+ grid_crops_coords = get_resize_crop_region_for_grid(
459
+ (grid_height, grid_width), base_size_width, base_size_height
460
+ )
461
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
462
+ embed_dim=self.transformer.config.attention_head_dim,
463
+ crops_coords=grid_crops_coords,
464
+ grid_size=(grid_height, grid_width),
465
+ temporal_size=num_frames,
466
+ use_real=True,
467
+ )
468
+
469
+ freqs_cos = freqs_cos.to(device=device)
470
+ freqs_sin = freqs_sin.to(device=device)
471
+ return freqs_cos, freqs_sin
472
+
473
+ @property
474
+ def guidance_scale(self):
475
+ return self._guidance_scale
476
+
477
+ @property
478
+ def num_timesteps(self):
479
+ return self._num_timesteps
480
+
481
+ @property
482
+ def interrupt(self):
483
+ return self._interrupt
484
+
485
+ @torch.no_grad()
486
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
487
+ def __call__(
488
+ self,
489
+ prompt: Optional[Union[str, List[str]]] = None,
490
+ negative_prompt: Optional[Union[str, List[str]]] = None,
491
+ height: int = 480,
492
+ width: int = 720,
493
+ num_frames: int = 49,
494
+ num_inference_steps: int = 50,
495
+ timesteps: Optional[List[int]] = None,
496
+ guidance_scale: float = 6,
497
+ use_dynamic_cfg: bool = False,
498
+ num_videos_per_prompt: int = 1,
499
+ eta: float = 0.0,
500
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
501
+ latents: Optional[torch.FloatTensor] = None,
502
+ prompt_embeds: Optional[torch.FloatTensor] = None,
503
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
504
+ output_type: str = "pil",
505
+ return_dict: bool = True,
506
+ callback_on_step_end: Optional[
507
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
508
+ ] = None,
509
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
510
+ max_sequence_length: int = 226,
511
+ ) -> Union[CogVideoXPipelineOutput, Tuple]:
512
+ """
513
+ Function invoked when calling the pipeline for generation.
514
+
515
+ Args:
516
+ prompt (`str` or `List[str]`, *optional*):
517
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
518
+ instead.
519
+ negative_prompt (`str` or `List[str]`, *optional*):
520
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
521
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
522
+ less than `1`).
523
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
524
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
525
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
526
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
527
+ num_frames (`int`, defaults to `48`):
528
+ Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
529
+ contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where
530
+ num_seconds is 6 and fps is 4. However, since videos can be saved at any fps, the only condition that
531
+ needs to be satisfied is that of divisibility mentioned above.
532
+ num_inference_steps (`int`, *optional*, defaults to 50):
533
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
534
+ expense of slower inference.
535
+ timesteps (`List[int]`, *optional*):
536
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
537
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
538
+ passed will be used. Must be in descending order.
539
+ guidance_scale (`float`, *optional*, defaults to 7.0):
540
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
541
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
542
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
543
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
544
+ usually at the expense of lower image quality.
545
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
546
+ The number of videos to generate per prompt.
547
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
548
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
549
+ to make generation deterministic.
550
+ latents (`torch.FloatTensor`, *optional*):
551
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
552
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
553
+ tensor will ge generated by sampling using the supplied random `generator`.
554
+ prompt_embeds (`torch.FloatTensor`, *optional*):
555
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
556
+ provided, text embeddings will be generated from `prompt` input argument.
557
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
558
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
559
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
560
+ argument.
561
+ output_type (`str`, *optional*, defaults to `"pil"`):
562
+ The output format of the generate image. Choose between
563
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
564
+ return_dict (`bool`, *optional*, defaults to `True`):
565
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
566
+ of a plain tuple.
567
+ callback_on_step_end (`Callable`, *optional*):
568
+ A function that calls at the end of each denoising steps during the inference. The function is called
569
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
570
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
571
+ `callback_on_step_end_tensor_inputs`.
572
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
573
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
574
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
575
+ `._callback_tensor_inputs` attribute of your pipeline class.
576
+ max_sequence_length (`int`, defaults to `226`):
577
+ Maximum sequence length in encoded prompt. Must be consistent with
578
+ `self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
579
+
580
+ Examples:
581
+
582
+ Returns:
583
+ [`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] or `tuple`:
584
+ [`~pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
585
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
586
+ """
587
+
588
+ if num_frames > 49:
589
+ raise ValueError(
590
+ "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."
591
+ )
592
+
593
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
594
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
595
+
596
+ height = height or self.transformer.config.sample_size * self.vae_scale_factor_spatial
597
+ width = width or self.transformer.config.sample_size * self.vae_scale_factor_spatial
598
+ num_videos_per_prompt = 1
599
+
600
+ # 1. Check inputs. Raise error if not correct
601
+ self.check_inputs(
602
+ prompt,
603
+ height,
604
+ width,
605
+ negative_prompt,
606
+ callback_on_step_end_tensor_inputs,
607
+ prompt_embeds,
608
+ negative_prompt_embeds,
609
+ )
610
+ self._guidance_scale = guidance_scale
611
+ self._interrupt = False
612
+
613
+ # 2. Default call parameters
614
+ if prompt is not None and isinstance(prompt, str):
615
+ batch_size = 1
616
+ elif prompt is not None and isinstance(prompt, list):
617
+ batch_size = len(prompt)
618
+ else:
619
+ batch_size = prompt_embeds.shape[0]
620
+
621
+ device = self._execution_device
622
+
623
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
624
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
625
+ # corresponds to doing no classifier free guidance.
626
+ do_classifier_free_guidance = guidance_scale > 1.0
627
+
628
+ # 3. Encode input prompt
629
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
630
+ prompt,
631
+ negative_prompt,
632
+ do_classifier_free_guidance,
633
+ num_videos_per_prompt=num_videos_per_prompt,
634
+ prompt_embeds=prompt_embeds,
635
+ negative_prompt_embeds=negative_prompt_embeds,
636
+ max_sequence_length=max_sequence_length,
637
+ device=device,
638
+ )
639
+ if do_classifier_free_guidance:
640
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
641
+
642
+ # 4. Prepare timesteps
643
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
644
+ self._num_timesteps = len(timesteps)
645
+
646
+ # 5. Prepare latents.
647
+ latent_channels = self.transformer.config.in_channels
648
+ latents = self.prepare_latents(
649
+ batch_size * num_videos_per_prompt,
650
+ latent_channels,
651
+ num_frames,
652
+ height,
653
+ width,
654
+ prompt_embeds.dtype,
655
+ device,
656
+ generator,
657
+ latents,
658
+ )
659
+
660
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
661
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
662
+
663
+ # 7. Create rotary embeds if required
664
+ image_rotary_emb = (
665
+ self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device)
666
+ if self.transformer.config.use_rotary_positional_embeddings
667
+ else None
668
+ )
669
+
670
+ # 8. Denoising loop
671
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
672
+
673
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
674
+ # for DPM-solver++
675
+ old_pred_original_sample = None
676
+ for i, t in enumerate(timesteps):
677
+ if self.interrupt:
678
+ continue
679
+
680
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
681
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
682
+
683
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
684
+ timestep = t.expand(latent_model_input.shape[0])
685
+
686
+ # predict noise model_output
687
+ noise_pred = self.transformer(
688
+ hidden_states=latent_model_input,
689
+ encoder_hidden_states=prompt_embeds,
690
+ timestep=timestep,
691
+ image_rotary_emb=image_rotary_emb,
692
+ return_dict=False,
693
+ )[0]
694
+ noise_pred = noise_pred.float()
695
+
696
+ # perform guidance
697
+ if use_dynamic_cfg:
698
+ self._guidance_scale = 1 + guidance_scale * (
699
+ (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
700
+ )
701
+ if do_classifier_free_guidance:
702
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
703
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
704
+
705
+ # compute the previous noisy sample x_t -> x_t-1
706
+ if not isinstance(self.scheduler, CogVideoXDPMScheduler):
707
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
708
+ else:
709
+ latents, old_pred_original_sample = self.scheduler.step(
710
+ noise_pred,
711
+ old_pred_original_sample,
712
+ t,
713
+ timesteps[i - 1] if i > 0 else None,
714
+ latents,
715
+ **extra_step_kwargs,
716
+ return_dict=False,
717
+ )
718
+ latents = latents.to(prompt_embeds.dtype)
719
+
720
+ # call the callback, if provided
721
+ if callback_on_step_end is not None:
722
+ callback_kwargs = {}
723
+ for k in callback_on_step_end_tensor_inputs:
724
+ callback_kwargs[k] = locals()[k]
725
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
726
+
727
+ latents = callback_outputs.pop("latents", latents)
728
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
729
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
730
+
731
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
732
+ progress_bar.update()
733
+
734
+ if not output_type == "latent":
735
+ video = self.decode_latents(latents)
736
+ video = self.video_processor.postprocess_video(video=video, output_type=output_type)
737
+ else:
738
+ video = latents
739
+
740
+ # Offload all models
741
+ self.maybe_free_model_hooks()
742
+
743
+ if not return_dict:
744
+ return (video,)
745
+
746
+ return CogVideoXPipelineOutput(frames=video)