diffusers 0.30.2__py3-none-any.whl → 0.31.0__py3-none-any.whl

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