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

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