diffusers 0.23.1__py3-none-any.whl → 0.24.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (176) hide show
  1. diffusers/__init__.py +16 -2
  2. diffusers/configuration_utils.py +1 -0
  3. diffusers/dependency_versions_check.py +0 -1
  4. diffusers/dependency_versions_table.py +4 -5
  5. diffusers/image_processor.py +186 -14
  6. diffusers/loaders/__init__.py +82 -0
  7. diffusers/loaders/ip_adapter.py +157 -0
  8. diffusers/loaders/lora.py +1415 -0
  9. diffusers/loaders/lora_conversion_utils.py +284 -0
  10. diffusers/loaders/single_file.py +631 -0
  11. diffusers/loaders/textual_inversion.py +459 -0
  12. diffusers/loaders/unet.py +735 -0
  13. diffusers/loaders/utils.py +59 -0
  14. diffusers/models/__init__.py +12 -1
  15. diffusers/models/attention.py +165 -14
  16. diffusers/models/attention_flax.py +9 -1
  17. diffusers/models/attention_processor.py +286 -1
  18. diffusers/models/autoencoder_asym_kl.py +14 -9
  19. diffusers/models/autoencoder_kl.py +3 -18
  20. diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
  21. diffusers/models/autoencoder_tiny.py +20 -24
  22. diffusers/models/consistency_decoder_vae.py +37 -30
  23. diffusers/models/controlnet.py +59 -39
  24. diffusers/models/controlnet_flax.py +19 -18
  25. diffusers/models/embeddings_flax.py +2 -0
  26. diffusers/models/lora.py +131 -1
  27. diffusers/models/modeling_flax_utils.py +2 -1
  28. diffusers/models/modeling_outputs.py +17 -0
  29. diffusers/models/modeling_utils.py +27 -19
  30. diffusers/models/normalization.py +2 -2
  31. diffusers/models/resnet.py +390 -59
  32. diffusers/models/transformer_2d.py +20 -3
  33. diffusers/models/transformer_temporal.py +183 -1
  34. diffusers/models/unet_2d_blocks_flax.py +5 -0
  35. diffusers/models/unet_2d_condition.py +9 -0
  36. diffusers/models/unet_2d_condition_flax.py +13 -13
  37. diffusers/models/unet_3d_blocks.py +957 -173
  38. diffusers/models/unet_3d_condition.py +16 -8
  39. diffusers/models/unet_kandi3.py +589 -0
  40. diffusers/models/unet_motion_model.py +48 -33
  41. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  42. diffusers/models/vae.py +63 -13
  43. diffusers/models/vae_flax.py +7 -0
  44. diffusers/models/vq_model.py +3 -1
  45. diffusers/optimization.py +16 -9
  46. diffusers/pipelines/__init__.py +65 -12
  47. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +93 -23
  48. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +97 -25
  49. diffusers/pipelines/animatediff/pipeline_animatediff.py +34 -4
  50. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  51. diffusers/pipelines/auto_pipeline.py +6 -0
  52. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  53. diffusers/pipelines/controlnet/pipeline_controlnet.py +217 -31
  54. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +101 -32
  55. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +136 -39
  56. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +119 -37
  57. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +196 -35
  58. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +102 -31
  59. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  60. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  61. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  62. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  63. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  64. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  65. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  66. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  67. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  68. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  69. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  70. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  71. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  72. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  73. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  74. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  75. diffusers/pipelines/kandinsky3/kandinsky3_pipeline.py +452 -0
  76. diffusers/pipelines/kandinsky3/kandinsky3img2img_pipeline.py +460 -0
  77. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +65 -6
  78. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +55 -3
  79. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  80. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  81. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  82. diffusers/pipelines/pipeline_flax_utils.py +4 -2
  83. diffusers/pipelines/pipeline_utils.py +33 -13
  84. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +196 -36
  85. diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py +1 -0
  86. diffusers/pipelines/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -0
  87. diffusers/pipelines/stable_diffusion/__init__.py +64 -21
  88. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +8 -3
  89. diffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +18 -2
  90. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  91. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  92. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  93. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +1 -0
  94. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +88 -9
  95. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +1 -0
  96. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  97. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py +1 -0
  98. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen.py +1 -0
  99. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen_text_image.py +1 -0
  100. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  101. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -9
  102. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -9
  103. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +1 -0
  104. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -13
  105. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -0
  106. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +1 -0
  107. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +1 -0
  108. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_model_editing.py +1 -0
  109. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -0
  110. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +1 -0
  111. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +1 -0
  112. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py +1 -0
  113. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +1 -0
  114. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +103 -8
  115. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +113 -8
  116. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +115 -9
  117. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -12
  118. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  119. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +649 -0
  120. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  121. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +109 -14
  122. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  123. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +1 -0
  124. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +18 -3
  125. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -2
  126. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +872 -0
  127. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +29 -40
  128. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -0
  129. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -0
  130. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -0
  131. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  132. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  133. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  134. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  135. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +1 -1
  136. diffusers/schedulers/__init__.py +2 -4
  137. diffusers/schedulers/deprecated/__init__.py +50 -0
  138. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  139. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  140. diffusers/schedulers/scheduling_ddim.py +1 -3
  141. diffusers/schedulers/scheduling_ddim_inverse.py +1 -3
  142. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  143. diffusers/schedulers/scheduling_ddpm.py +1 -3
  144. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -3
  145. diffusers/schedulers/scheduling_deis_multistep.py +15 -5
  146. diffusers/schedulers/scheduling_dpmsolver_multistep.py +15 -5
  147. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +15 -5
  148. diffusers/schedulers/scheduling_dpmsolver_sde.py +1 -3
  149. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +15 -5
  150. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +1 -3
  151. diffusers/schedulers/scheduling_euler_discrete.py +40 -13
  152. diffusers/schedulers/scheduling_heun_discrete.py +15 -5
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +15 -5
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +15 -5
  155. diffusers/schedulers/scheduling_lcm.py +123 -29
  156. diffusers/schedulers/scheduling_lms_discrete.py +1 -3
  157. diffusers/schedulers/scheduling_pndm.py +1 -3
  158. diffusers/schedulers/scheduling_repaint.py +1 -3
  159. diffusers/schedulers/scheduling_unipc_multistep.py +15 -5
  160. diffusers/utils/__init__.py +1 -0
  161. diffusers/utils/constants.py +8 -7
  162. diffusers/utils/dummy_pt_objects.py +45 -0
  163. diffusers/utils/dummy_torch_and_transformers_objects.py +60 -0
  164. diffusers/utils/dynamic_modules_utils.py +4 -4
  165. diffusers/utils/export_utils.py +8 -3
  166. diffusers/utils/logging.py +10 -10
  167. diffusers/utils/outputs.py +5 -5
  168. diffusers/utils/peft_utils.py +88 -44
  169. diffusers/utils/torch_utils.py +2 -2
  170. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/METADATA +38 -22
  171. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/RECORD +175 -157
  172. diffusers/loaders.py +0 -3336
  173. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
  174. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/WHEEL +0 -0
  175. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +0 -0
  176. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,649 @@
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from dataclasses import dataclass
17
+ from typing import Callable, Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
23
+
24
+ from ...image_processor import VaeImageProcessor
25
+ from ...models import AutoencoderKLTemporalDecoder, UNetSpatioTemporalConditionModel
26
+ from ...schedulers import EulerDiscreteScheduler
27
+ from ...utils import BaseOutput, logging
28
+ from ...utils.torch_utils import randn_tensor
29
+ from ..pipeline_utils import DiffusionPipeline
30
+
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+
35
+ def _append_dims(x, target_dims):
36
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
37
+ dims_to_append = target_dims - x.ndim
38
+ if dims_to_append < 0:
39
+ raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
40
+ return x[(...,) + (None,) * dims_to_append]
41
+
42
+
43
+ def tensor2vid(video: torch.Tensor, processor, output_type="np"):
44
+ # Based on:
45
+ # https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
46
+
47
+ batch_size, channels, num_frames, height, width = video.shape
48
+ outputs = []
49
+ for batch_idx in range(batch_size):
50
+ batch_vid = video[batch_idx].permute(1, 0, 2, 3)
51
+ batch_output = processor.postprocess(batch_vid, output_type)
52
+
53
+ outputs.append(batch_output)
54
+
55
+ return outputs
56
+
57
+
58
+ @dataclass
59
+ class StableVideoDiffusionPipelineOutput(BaseOutput):
60
+ r"""
61
+ Output class for zero-shot text-to-video pipeline.
62
+
63
+ Args:
64
+ frames (`[List[PIL.Image.Image]`, `np.ndarray`]):
65
+ List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
66
+ num_channels)`.
67
+ """
68
+
69
+ frames: Union[List[PIL.Image.Image], np.ndarray]
70
+
71
+
72
+ class StableVideoDiffusionPipeline(DiffusionPipeline):
73
+ r"""
74
+ Pipeline to generate video from an input image using Stable Video Diffusion.
75
+
76
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
77
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
78
+
79
+ Args:
80
+ vae ([`AutoencoderKL`]):
81
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
82
+ image_encoder ([`~transformers.CLIPVisionModelWithProjection`]):
83
+ Frozen CLIP image-encoder ([laion/CLIP-ViT-H-14-laion2B-s32B-b79K](https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K)).
84
+ unet ([`UNetSpatioTemporalConditionModel`]):
85
+ A `UNetSpatioTemporalConditionModel` to denoise the encoded image latents.
86
+ scheduler ([`EulerDiscreteScheduler`]):
87
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents.
88
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
89
+ A `CLIPImageProcessor` to extract features from generated images.
90
+ """
91
+
92
+ model_cpu_offload_seq = "image_encoder->unet->vae"
93
+ _callback_tensor_inputs = ["latents"]
94
+
95
+ def __init__(
96
+ self,
97
+ vae: AutoencoderKLTemporalDecoder,
98
+ image_encoder: CLIPVisionModelWithProjection,
99
+ unet: UNetSpatioTemporalConditionModel,
100
+ scheduler: EulerDiscreteScheduler,
101
+ feature_extractor: CLIPImageProcessor,
102
+ ):
103
+ super().__init__()
104
+
105
+ self.register_modules(
106
+ vae=vae,
107
+ image_encoder=image_encoder,
108
+ unet=unet,
109
+ scheduler=scheduler,
110
+ feature_extractor=feature_extractor,
111
+ )
112
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
113
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
114
+
115
+ def _encode_image(self, image, device, num_videos_per_prompt, do_classifier_free_guidance):
116
+ dtype = next(self.image_encoder.parameters()).dtype
117
+
118
+ if not isinstance(image, torch.Tensor):
119
+ image = self.image_processor.pil_to_numpy(image)
120
+ image = self.image_processor.numpy_to_pt(image)
121
+
122
+ # We normalize the image before resizing to match with the original implementation.
123
+ # Then we unnormalize it after resizing.
124
+ image = image * 2.0 - 1.0
125
+ image = _resize_with_antialiasing(image, (224, 224))
126
+ image = (image + 1.0) / 2.0
127
+
128
+ # Normalize the image with for CLIP input
129
+ image = self.feature_extractor(
130
+ images=image,
131
+ do_normalize=True,
132
+ do_center_crop=False,
133
+ do_resize=False,
134
+ do_rescale=False,
135
+ return_tensors="pt",
136
+ ).pixel_values
137
+
138
+ image = image.to(device=device, dtype=dtype)
139
+ image_embeddings = self.image_encoder(image).image_embeds
140
+ image_embeddings = image_embeddings.unsqueeze(1)
141
+
142
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
143
+ bs_embed, seq_len, _ = image_embeddings.shape
144
+ image_embeddings = image_embeddings.repeat(1, num_videos_per_prompt, 1)
145
+ image_embeddings = image_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1)
146
+
147
+ if do_classifier_free_guidance:
148
+ negative_image_embeddings = torch.zeros_like(image_embeddings)
149
+
150
+ # For classifier free guidance, we need to do two forward passes.
151
+ # Here we concatenate the unconditional and text embeddings into a single batch
152
+ # to avoid doing two forward passes
153
+ image_embeddings = torch.cat([negative_image_embeddings, image_embeddings])
154
+
155
+ return image_embeddings
156
+
157
+ def _encode_vae_image(
158
+ self,
159
+ image: torch.Tensor,
160
+ device,
161
+ num_videos_per_prompt,
162
+ do_classifier_free_guidance,
163
+ ):
164
+ image = image.to(device=device)
165
+ image_latents = self.vae.encode(image).latent_dist.mode()
166
+
167
+ if do_classifier_free_guidance:
168
+ negative_image_latents = torch.zeros_like(image_latents)
169
+
170
+ # For classifier free guidance, we need to do two forward passes.
171
+ # Here we concatenate the unconditional and text embeddings into a single batch
172
+ # to avoid doing two forward passes
173
+ image_latents = torch.cat([negative_image_latents, image_latents])
174
+
175
+ # duplicate image_latents for each generation per prompt, using mps friendly method
176
+ image_latents = image_latents.repeat(num_videos_per_prompt, 1, 1, 1)
177
+
178
+ return image_latents
179
+
180
+ def _get_add_time_ids(
181
+ self,
182
+ fps,
183
+ motion_bucket_id,
184
+ noise_aug_strength,
185
+ dtype,
186
+ batch_size,
187
+ num_videos_per_prompt,
188
+ do_classifier_free_guidance,
189
+ ):
190
+ add_time_ids = [fps, motion_bucket_id, noise_aug_strength]
191
+
192
+ passed_add_embed_dim = self.unet.config.addition_time_embed_dim * len(add_time_ids)
193
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
194
+
195
+ if expected_add_embed_dim != passed_add_embed_dim:
196
+ raise ValueError(
197
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
198
+ )
199
+
200
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
201
+ add_time_ids = add_time_ids.repeat(batch_size * num_videos_per_prompt, 1)
202
+
203
+ if do_classifier_free_guidance:
204
+ add_time_ids = torch.cat([add_time_ids, add_time_ids])
205
+
206
+ return add_time_ids
207
+
208
+ def decode_latents(self, latents, num_frames, decode_chunk_size=14):
209
+ # [batch, frames, channels, height, width] -> [batch*frames, channels, height, width]
210
+ latents = latents.flatten(0, 1)
211
+
212
+ latents = 1 / self.vae.config.scaling_factor * latents
213
+
214
+ accepts_num_frames = "num_frames" in set(inspect.signature(self.vae.forward).parameters.keys())
215
+
216
+ # decode decode_chunk_size frames at a time to avoid OOM
217
+ frames = []
218
+ for i in range(0, latents.shape[0], decode_chunk_size):
219
+ num_frames_in = latents[i : i + decode_chunk_size].shape[0]
220
+ decode_kwargs = {}
221
+ if accepts_num_frames:
222
+ # we only pass num_frames_in if it's expected
223
+ decode_kwargs["num_frames"] = num_frames_in
224
+
225
+ frame = self.vae.decode(latents[i : i + decode_chunk_size], **decode_kwargs).sample
226
+ frames.append(frame)
227
+ frames = torch.cat(frames, dim=0)
228
+
229
+ # [batch*frames, channels, height, width] -> [batch, channels, frames, height, width]
230
+ frames = frames.reshape(-1, num_frames, *frames.shape[1:]).permute(0, 2, 1, 3, 4)
231
+
232
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
233
+ frames = frames.float()
234
+ return frames
235
+
236
+ def check_inputs(self, image, height, width):
237
+ if (
238
+ not isinstance(image, torch.Tensor)
239
+ and not isinstance(image, PIL.Image.Image)
240
+ and not isinstance(image, list)
241
+ ):
242
+ raise ValueError(
243
+ "`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
244
+ f" {type(image)}"
245
+ )
246
+
247
+ if height % 8 != 0 or width % 8 != 0:
248
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
249
+
250
+ def prepare_latents(
251
+ self,
252
+ batch_size,
253
+ num_frames,
254
+ num_channels_latents,
255
+ height,
256
+ width,
257
+ dtype,
258
+ device,
259
+ generator,
260
+ latents=None,
261
+ ):
262
+ shape = (
263
+ batch_size,
264
+ num_frames,
265
+ num_channels_latents // 2,
266
+ height // self.vae_scale_factor,
267
+ width // self.vae_scale_factor,
268
+ )
269
+ if isinstance(generator, list) and len(generator) != batch_size:
270
+ raise ValueError(
271
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
272
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
273
+ )
274
+
275
+ if latents is None:
276
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
277
+ else:
278
+ latents = latents.to(device)
279
+
280
+ # scale the initial noise by the standard deviation required by the scheduler
281
+ latents = latents * self.scheduler.init_noise_sigma
282
+ return latents
283
+
284
+ @property
285
+ def guidance_scale(self):
286
+ return self._guidance_scale
287
+
288
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
289
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
290
+ # corresponds to doing no classifier free guidance.
291
+ @property
292
+ def do_classifier_free_guidance(self):
293
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
294
+
295
+ @property
296
+ def num_timesteps(self):
297
+ return self._num_timesteps
298
+
299
+ @torch.no_grad()
300
+ def __call__(
301
+ self,
302
+ image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
303
+ height: int = 576,
304
+ width: int = 1024,
305
+ num_frames: Optional[int] = None,
306
+ num_inference_steps: int = 25,
307
+ min_guidance_scale: float = 1.0,
308
+ max_guidance_scale: float = 3.0,
309
+ fps: int = 7,
310
+ motion_bucket_id: int = 127,
311
+ noise_aug_strength: int = 0.02,
312
+ decode_chunk_size: Optional[int] = None,
313
+ num_videos_per_prompt: Optional[int] = 1,
314
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
315
+ latents: Optional[torch.FloatTensor] = None,
316
+ output_type: Optional[str] = "pil",
317
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
318
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
319
+ return_dict: bool = True,
320
+ ):
321
+ r"""
322
+ The call function to the pipeline for generation.
323
+
324
+ Args:
325
+ image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
326
+ Image or images to guide image generation. If you provide a tensor, it needs to be compatible with
327
+ [`CLIPImageProcessor`](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json).
328
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
329
+ The height in pixels of the generated image.
330
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
331
+ The width in pixels of the generated image.
332
+ num_frames (`int`, *optional*):
333
+ The number of video frames to generate. Defaults to 14 for `stable-video-diffusion-img2vid` and to 25 for `stable-video-diffusion-img2vid-xt`
334
+ num_inference_steps (`int`, *optional*, defaults to 25):
335
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
336
+ expense of slower inference. This parameter is modulated by `strength`.
337
+ min_guidance_scale (`float`, *optional*, defaults to 1.0):
338
+ The minimum guidance scale. Used for the classifier free guidance with first frame.
339
+ max_guidance_scale (`float`, *optional*, defaults to 3.0):
340
+ The maximum guidance scale. Used for the classifier free guidance with last frame.
341
+ fps (`int`, *optional*, defaults to 7):
342
+ Frames per second. The rate at which the generated images shall be exported to a video after generation.
343
+ Note that Stable Diffusion Video's UNet was micro-conditioned on fps-1 during training.
344
+ motion_bucket_id (`int`, *optional*, defaults to 127):
345
+ The motion bucket ID. Used as conditioning for the generation. The higher the number the more motion will be in the video.
346
+ noise_aug_strength (`int`, *optional*, defaults to 0.02):
347
+ The amount of noise added to the init image, the higher it is the less the video will look like the init image. Increase it for more motion.
348
+ decode_chunk_size (`int`, *optional*):
349
+ The number of frames to decode at a time. The higher the chunk size, the higher the temporal consistency
350
+ between frames, but also the higher the memory consumption. By default, the decoder will decode all frames at once
351
+ for maximal quality. Reduce `decode_chunk_size` to reduce memory usage.
352
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
353
+ The number of images to generate per prompt.
354
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
355
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
356
+ generation deterministic.
357
+ latents (`torch.FloatTensor`, *optional*):
358
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
359
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
360
+ tensor is generated by sampling using the supplied random `generator`.
361
+ output_type (`str`, *optional*, defaults to `"pil"`):
362
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
363
+ callback_on_step_end (`Callable`, *optional*):
364
+ A function that calls at the end of each denoising steps during the inference. The function is called
365
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
366
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
367
+ `callback_on_step_end_tensor_inputs`.
368
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
369
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
370
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
371
+ `._callback_tensor_inputs` attribute of your pipeline class.
372
+ return_dict (`bool`, *optional*, defaults to `True`):
373
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
374
+ plain tuple.
375
+
376
+ Returns:
377
+ [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] or `tuple`:
378
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] is returned,
379
+ otherwise a `tuple` is returned where the first element is a list of list with the generated frames.
380
+
381
+ Examples:
382
+
383
+ ```py
384
+ from diffusers import StableVideoDiffusionPipeline
385
+ from diffusers.utils import load_image, export_to_video
386
+
387
+ pipe = StableVideoDiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16")
388
+ pipe.to("cuda")
389
+
390
+ image = load_image("https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200")
391
+ image = image.resize((1024, 576))
392
+
393
+ frames = pipe(image, num_frames=25, decode_chunk_size=8).frames[0]
394
+ export_to_video(frames, "generated.mp4", fps=7)
395
+ ```
396
+ """
397
+ # 0. Default height and width to unet
398
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
399
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
400
+
401
+ num_frames = num_frames if num_frames is not None else self.unet.config.num_frames
402
+ decode_chunk_size = decode_chunk_size if decode_chunk_size is not None else num_frames
403
+
404
+ # 1. Check inputs. Raise error if not correct
405
+ self.check_inputs(image, height, width)
406
+
407
+ # 2. Define call parameters
408
+ if isinstance(image, PIL.Image.Image):
409
+ batch_size = 1
410
+ elif isinstance(image, list):
411
+ batch_size = len(image)
412
+ else:
413
+ batch_size = image.shape[0]
414
+ device = self._execution_device
415
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
416
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
417
+ # corresponds to doing no classifier free guidance.
418
+ do_classifier_free_guidance = max_guidance_scale > 1.0
419
+
420
+ # 3. Encode input image
421
+ image_embeddings = self._encode_image(image, device, num_videos_per_prompt, do_classifier_free_guidance)
422
+
423
+ # NOTE: Stable Diffusion Video was conditioned on fps - 1, which
424
+ # is why it is reduced here.
425
+ # See: https://github.com/Stability-AI/generative-models/blob/ed0997173f98eaf8f4edf7ba5fe8f15c6b877fd3/scripts/sampling/simple_video_sample.py#L188
426
+ fps = fps - 1
427
+
428
+ # 4. Encode input image using VAE
429
+ image = self.image_processor.preprocess(image, height=height, width=width)
430
+ noise = randn_tensor(image.shape, generator=generator, device=image.device, dtype=image.dtype)
431
+ image = image + noise_aug_strength * noise
432
+
433
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
434
+ if needs_upcasting:
435
+ self.vae.to(dtype=torch.float32)
436
+
437
+ image_latents = self._encode_vae_image(image, device, num_videos_per_prompt, do_classifier_free_guidance)
438
+ image_latents = image_latents.to(image_embeddings.dtype)
439
+
440
+ # cast back to fp16 if needed
441
+ if needs_upcasting:
442
+ self.vae.to(dtype=torch.float16)
443
+
444
+ # Repeat the image latents for each frame so we can concatenate them with the noise
445
+ # image_latents [batch, channels, height, width] ->[batch, num_frames, channels, height, width]
446
+ image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1)
447
+
448
+ # 5. Get Added Time IDs
449
+ added_time_ids = self._get_add_time_ids(
450
+ fps,
451
+ motion_bucket_id,
452
+ noise_aug_strength,
453
+ image_embeddings.dtype,
454
+ batch_size,
455
+ num_videos_per_prompt,
456
+ do_classifier_free_guidance,
457
+ )
458
+ added_time_ids = added_time_ids.to(device)
459
+
460
+ # 4. Prepare timesteps
461
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
462
+ timesteps = self.scheduler.timesteps
463
+
464
+ # 5. Prepare latent variables
465
+ num_channels_latents = self.unet.config.in_channels
466
+ latents = self.prepare_latents(
467
+ batch_size * num_videos_per_prompt,
468
+ num_frames,
469
+ num_channels_latents,
470
+ height,
471
+ width,
472
+ image_embeddings.dtype,
473
+ device,
474
+ generator,
475
+ latents,
476
+ )
477
+
478
+ # 7. Prepare guidance scale
479
+ guidance_scale = torch.linspace(min_guidance_scale, max_guidance_scale, num_frames).unsqueeze(0)
480
+ guidance_scale = guidance_scale.to(device, latents.dtype)
481
+ guidance_scale = guidance_scale.repeat(batch_size * num_videos_per_prompt, 1)
482
+ guidance_scale = _append_dims(guidance_scale, latents.ndim)
483
+
484
+ self._guidance_scale = guidance_scale
485
+
486
+ # 8. Denoising loop
487
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
488
+ self._num_timesteps = len(timesteps)
489
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
490
+ for i, t in enumerate(timesteps):
491
+ # expand the latents if we are doing classifier free guidance
492
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
493
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
494
+
495
+ # Concatenate image_latents over channels dimention
496
+ latent_model_input = torch.cat([latent_model_input, image_latents], dim=2)
497
+
498
+ # predict the noise residual
499
+ noise_pred = self.unet(
500
+ latent_model_input,
501
+ t,
502
+ encoder_hidden_states=image_embeddings,
503
+ added_time_ids=added_time_ids,
504
+ return_dict=False,
505
+ )[0]
506
+
507
+ # perform guidance
508
+ if do_classifier_free_guidance:
509
+ noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
510
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)
511
+
512
+ # compute the previous noisy sample x_t -> x_t-1
513
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
514
+
515
+ if callback_on_step_end is not None:
516
+ callback_kwargs = {}
517
+ for k in callback_on_step_end_tensor_inputs:
518
+ callback_kwargs[k] = locals()[k]
519
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
520
+
521
+ latents = callback_outputs.pop("latents", latents)
522
+
523
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
524
+ progress_bar.update()
525
+
526
+ if not output_type == "latent":
527
+ # cast back to fp16 if needed
528
+ if needs_upcasting:
529
+ self.vae.to(dtype=torch.float16)
530
+ frames = self.decode_latents(latents, num_frames, decode_chunk_size)
531
+ frames = tensor2vid(frames, self.image_processor, output_type=output_type)
532
+ else:
533
+ frames = latents
534
+
535
+ self.maybe_free_model_hooks()
536
+
537
+ if not return_dict:
538
+ return frames
539
+
540
+ return StableVideoDiffusionPipelineOutput(frames=frames)
541
+
542
+
543
+ # resizing utils
544
+ # TODO: clean up later
545
+ def _resize_with_antialiasing(input, size, interpolation="bicubic", align_corners=True):
546
+ h, w = input.shape[-2:]
547
+ factors = (h / size[0], w / size[1])
548
+
549
+ # First, we have to determine sigma
550
+ # Taken from skimage: https://github.com/scikit-image/scikit-image/blob/v0.19.2/skimage/transform/_warps.py#L171
551
+ sigmas = (
552
+ max((factors[0] - 1.0) / 2.0, 0.001),
553
+ max((factors[1] - 1.0) / 2.0, 0.001),
554
+ )
555
+
556
+ # Now kernel size. Good results are for 3 sigma, but that is kind of slow. Pillow uses 1 sigma
557
+ # https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206
558
+ # But they do it in the 2 passes, which gives better results. Let's try 2 sigmas for now
559
+ ks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3))
560
+
561
+ # Make sure it is odd
562
+ if (ks[0] % 2) == 0:
563
+ ks = ks[0] + 1, ks[1]
564
+
565
+ if (ks[1] % 2) == 0:
566
+ ks = ks[0], ks[1] + 1
567
+
568
+ input = _gaussian_blur2d(input, ks, sigmas)
569
+
570
+ output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)
571
+ return output
572
+
573
+
574
+ def _compute_padding(kernel_size):
575
+ """Compute padding tuple."""
576
+ # 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)
577
+ # https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad
578
+ if len(kernel_size) < 2:
579
+ raise AssertionError(kernel_size)
580
+ computed = [k - 1 for k in kernel_size]
581
+
582
+ # for even kernels we need to do asymmetric padding :(
583
+ out_padding = 2 * len(kernel_size) * [0]
584
+
585
+ for i in range(len(kernel_size)):
586
+ computed_tmp = computed[-(i + 1)]
587
+
588
+ pad_front = computed_tmp // 2
589
+ pad_rear = computed_tmp - pad_front
590
+
591
+ out_padding[2 * i + 0] = pad_front
592
+ out_padding[2 * i + 1] = pad_rear
593
+
594
+ return out_padding
595
+
596
+
597
+ def _filter2d(input, kernel):
598
+ # prepare kernel
599
+ b, c, h, w = input.shape
600
+ tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
601
+
602
+ tmp_kernel = tmp_kernel.expand(-1, c, -1, -1)
603
+
604
+ height, width = tmp_kernel.shape[-2:]
605
+
606
+ padding_shape: list[int] = _compute_padding([height, width])
607
+ input = torch.nn.functional.pad(input, padding_shape, mode="reflect")
608
+
609
+ # kernel and input tensor reshape to align element-wise or batch-wise params
610
+ tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)
611
+ input = input.view(-1, tmp_kernel.size(0), input.size(-2), input.size(-1))
612
+
613
+ # convolve the tensor with the kernel.
614
+ output = torch.nn.functional.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
615
+
616
+ out = output.view(b, c, h, w)
617
+ return out
618
+
619
+
620
+ def _gaussian(window_size: int, sigma):
621
+ if isinstance(sigma, float):
622
+ sigma = torch.tensor([[sigma]])
623
+
624
+ batch_size = sigma.shape[0]
625
+
626
+ x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)
627
+
628
+ if window_size % 2 == 0:
629
+ x = x + 0.5
630
+
631
+ gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0)))
632
+
633
+ return gauss / gauss.sum(-1, keepdim=True)
634
+
635
+
636
+ def _gaussian_blur2d(input, kernel_size, sigma):
637
+ if isinstance(sigma, tuple):
638
+ sigma = torch.tensor([sigma], dtype=input.dtype)
639
+ else:
640
+ sigma = sigma.to(dtype=input.dtype)
641
+
642
+ ky, kx = int(kernel_size[0]), int(kernel_size[1])
643
+ bs = sigma.shape[0]
644
+ kernel_x = _gaussian(kx, sigma[:, 1].view(bs, 1))
645
+ kernel_y = _gaussian(ky, sigma[:, 0].view(bs, 1))
646
+ out_x = _filter2d(input, kernel_x[..., None, :])
647
+ out = _filter2d(out_x, kernel_y[..., None])
648
+
649
+ return out