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