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