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,654 @@
1
+ import inspect
2
+ from typing import Callable, Dict, List, Optional, Union
3
+
4
+ import numpy as np
5
+ import PIL
6
+ import PIL.Image
7
+ import torch
8
+ from transformers import T5EncoderModel, T5Tokenizer
9
+
10
+ from ...loaders import LoraLoaderMixin
11
+ from ...models import Kandinsky3UNet, VQModel
12
+ from ...schedulers import DDPMScheduler
13
+ from ...utils import (
14
+ deprecate,
15
+ is_accelerate_available,
16
+ logging,
17
+ replace_example_docstring,
18
+ )
19
+ from ...utils.torch_utils import randn_tensor
20
+ from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
21
+
22
+
23
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
24
+
25
+ EXAMPLE_DOC_STRING = """
26
+ Examples:
27
+ ```py
28
+ >>> from diffusers import AutoPipelineForImage2Image
29
+ >>> from diffusers.utils import load_image
30
+ >>> import torch
31
+
32
+ >>> pipe = AutoPipelineForImage2Image.from_pretrained("kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16)
33
+ >>> pipe.enable_model_cpu_offload()
34
+
35
+ >>> prompt = "A painting of the inside of a subway train with tiny raccoons."
36
+ >>> image = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky3/t2i.png")
37
+
38
+ >>> generator = torch.Generator(device="cpu").manual_seed(0)
39
+ >>> image = pipe(prompt, image=image, strength=0.75, num_inference_steps=25, generator=generator).images[0]
40
+ ```
41
+ """
42
+
43
+
44
+ def downscale_height_and_width(height, width, scale_factor=8):
45
+ new_height = height // scale_factor**2
46
+ if height % scale_factor**2 != 0:
47
+ new_height += 1
48
+ new_width = width // scale_factor**2
49
+ if width % scale_factor**2 != 0:
50
+ new_width += 1
51
+ return new_height * scale_factor, new_width * scale_factor
52
+
53
+
54
+ def prepare_image(pil_image):
55
+ arr = np.array(pil_image.convert("RGB"))
56
+ arr = arr.astype(np.float32) / 127.5 - 1
57
+ arr = np.transpose(arr, [2, 0, 1])
58
+ image = torch.from_numpy(arr).unsqueeze(0)
59
+ return image
60
+
61
+
62
+ class Kandinsky3Img2ImgPipeline(DiffusionPipeline, LoraLoaderMixin):
63
+ model_cpu_offload_seq = "text_encoder->movq->unet->movq"
64
+ _callback_tensor_inputs = [
65
+ "latents",
66
+ "prompt_embeds",
67
+ "negative_prompt_embeds",
68
+ "negative_attention_mask",
69
+ "attention_mask",
70
+ ]
71
+
72
+ def __init__(
73
+ self,
74
+ tokenizer: T5Tokenizer,
75
+ text_encoder: T5EncoderModel,
76
+ unet: Kandinsky3UNet,
77
+ scheduler: DDPMScheduler,
78
+ movq: VQModel,
79
+ ):
80
+ super().__init__()
81
+
82
+ self.register_modules(
83
+ tokenizer=tokenizer, text_encoder=text_encoder, unet=unet, scheduler=scheduler, movq=movq
84
+ )
85
+
86
+ def get_timesteps(self, num_inference_steps, strength, device):
87
+ # get the original timestep using init_timestep
88
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
89
+
90
+ t_start = max(num_inference_steps - init_timestep, 0)
91
+ timesteps = self.scheduler.timesteps[t_start:]
92
+
93
+ return timesteps, num_inference_steps - t_start
94
+
95
+ def remove_all_hooks(self):
96
+ if is_accelerate_available():
97
+ from accelerate.hooks import remove_hook_from_module
98
+ else:
99
+ raise ImportError("Please install accelerate via `pip install accelerate`")
100
+
101
+ for model in [self.text_encoder, self.unet]:
102
+ if model is not None:
103
+ remove_hook_from_module(model, recurse=True)
104
+
105
+ self.unet_offload_hook = None
106
+ self.text_encoder_offload_hook = None
107
+ self.final_offload_hook = None
108
+
109
+ def _process_embeds(self, embeddings, attention_mask, cut_context):
110
+ # return embeddings, attention_mask
111
+ if cut_context:
112
+ embeddings[attention_mask == 0] = torch.zeros_like(embeddings[attention_mask == 0])
113
+ max_seq_length = attention_mask.sum(-1).max() + 1
114
+ embeddings = embeddings[:, :max_seq_length]
115
+ attention_mask = attention_mask[:, :max_seq_length]
116
+ return embeddings, attention_mask
117
+
118
+ @torch.no_grad()
119
+ def encode_prompt(
120
+ self,
121
+ prompt,
122
+ do_classifier_free_guidance=True,
123
+ num_images_per_prompt=1,
124
+ device=None,
125
+ negative_prompt=None,
126
+ prompt_embeds: Optional[torch.FloatTensor] = None,
127
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
128
+ _cut_context=False,
129
+ attention_mask: Optional[torch.FloatTensor] = None,
130
+ negative_attention_mask: Optional[torch.FloatTensor] = None,
131
+ ):
132
+ r"""
133
+ Encodes the prompt into text encoder hidden states.
134
+
135
+ Args:
136
+ prompt (`str` or `List[str]`, *optional*):
137
+ prompt to be encoded
138
+ device: (`torch.device`, *optional*):
139
+ torch device to place the resulting embeddings on
140
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
141
+ number of images that should be generated per prompt
142
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
143
+ whether to use classifier free guidance or not
144
+ negative_prompt (`str` or `List[str]`, *optional*):
145
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
146
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
147
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
148
+ prompt_embeds (`torch.FloatTensor`, *optional*):
149
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
150
+ provided, text embeddings will be generated from `prompt` input argument.
151
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
152
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
153
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
154
+ argument.
155
+ attention_mask (`torch.FloatTensor`, *optional*):
156
+ Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
157
+ negative_attention_mask (`torch.FloatTensor`, *optional*):
158
+ Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
159
+ """
160
+ if prompt is not None and negative_prompt is not None:
161
+ if type(prompt) is not type(negative_prompt):
162
+ raise TypeError(
163
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
164
+ f" {type(prompt)}."
165
+ )
166
+
167
+ if device is None:
168
+ device = self._execution_device
169
+
170
+ if prompt is not None and isinstance(prompt, str):
171
+ batch_size = 1
172
+ elif prompt is not None and isinstance(prompt, list):
173
+ batch_size = len(prompt)
174
+ else:
175
+ batch_size = prompt_embeds.shape[0]
176
+
177
+ max_length = 128
178
+
179
+ if prompt_embeds is None:
180
+ text_inputs = self.tokenizer(
181
+ prompt,
182
+ padding="max_length",
183
+ max_length=max_length,
184
+ truncation=True,
185
+ return_tensors="pt",
186
+ )
187
+ text_input_ids = text_inputs.input_ids.to(device)
188
+ attention_mask = text_inputs.attention_mask.to(device)
189
+ prompt_embeds = self.text_encoder(
190
+ text_input_ids,
191
+ attention_mask=attention_mask,
192
+ )
193
+ prompt_embeds = prompt_embeds[0]
194
+ prompt_embeds, attention_mask = self._process_embeds(prompt_embeds, attention_mask, _cut_context)
195
+ prompt_embeds = prompt_embeds * attention_mask.unsqueeze(2)
196
+
197
+ if self.text_encoder is not None:
198
+ dtype = self.text_encoder.dtype
199
+ else:
200
+ dtype = None
201
+
202
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
203
+
204
+ bs_embed, seq_len, _ = prompt_embeds.shape
205
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
206
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
207
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
208
+ attention_mask = attention_mask.repeat(num_images_per_prompt, 1)
209
+ # get unconditional embeddings for classifier free guidance
210
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
211
+ uncond_tokens: List[str]
212
+
213
+ if negative_prompt is None:
214
+ uncond_tokens = [""] * batch_size
215
+ elif isinstance(negative_prompt, str):
216
+ uncond_tokens = [negative_prompt]
217
+ elif batch_size != len(negative_prompt):
218
+ raise ValueError(
219
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
220
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
221
+ " the batch size of `prompt`."
222
+ )
223
+ else:
224
+ uncond_tokens = negative_prompt
225
+ if negative_prompt is not None:
226
+ uncond_input = self.tokenizer(
227
+ uncond_tokens,
228
+ padding="max_length",
229
+ max_length=128,
230
+ truncation=True,
231
+ return_attention_mask=True,
232
+ return_tensors="pt",
233
+ )
234
+ text_input_ids = uncond_input.input_ids.to(device)
235
+ negative_attention_mask = uncond_input.attention_mask.to(device)
236
+
237
+ negative_prompt_embeds = self.text_encoder(
238
+ text_input_ids,
239
+ attention_mask=negative_attention_mask,
240
+ )
241
+ negative_prompt_embeds = negative_prompt_embeds[0]
242
+ negative_prompt_embeds = negative_prompt_embeds[:, : prompt_embeds.shape[1]]
243
+ negative_attention_mask = negative_attention_mask[:, : prompt_embeds.shape[1]]
244
+ negative_prompt_embeds = negative_prompt_embeds * negative_attention_mask.unsqueeze(2)
245
+
246
+ else:
247
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
248
+ negative_attention_mask = torch.zeros_like(attention_mask)
249
+
250
+ if do_classifier_free_guidance:
251
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
252
+ seq_len = negative_prompt_embeds.shape[1]
253
+
254
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
255
+ if negative_prompt_embeds.shape != prompt_embeds.shape:
256
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
257
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
258
+ negative_attention_mask = negative_attention_mask.repeat(num_images_per_prompt, 1)
259
+
260
+ # For classifier free guidance, we need to do two forward passes.
261
+ # Here we concatenate the unconditional and text embeddings into a single batch
262
+ # to avoid doing two forward passes
263
+ else:
264
+ negative_prompt_embeds = None
265
+ negative_attention_mask = None
266
+ return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask
267
+
268
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
269
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
270
+ raise ValueError(
271
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
272
+ )
273
+
274
+ image = image.to(device=device, dtype=dtype)
275
+
276
+ batch_size = batch_size * num_images_per_prompt
277
+
278
+ if image.shape[1] == 4:
279
+ init_latents = image
280
+
281
+ else:
282
+ if isinstance(generator, list) and len(generator) != batch_size:
283
+ raise ValueError(
284
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
285
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
286
+ )
287
+
288
+ elif isinstance(generator, list):
289
+ init_latents = [
290
+ self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
291
+ ]
292
+ init_latents = torch.cat(init_latents, dim=0)
293
+ else:
294
+ init_latents = self.movq.encode(image).latent_dist.sample(generator)
295
+
296
+ init_latents = self.movq.config.scaling_factor * init_latents
297
+
298
+ init_latents = torch.cat([init_latents], dim=0)
299
+
300
+ shape = init_latents.shape
301
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
302
+
303
+ # get latents
304
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
305
+
306
+ latents = init_latents
307
+
308
+ return latents
309
+
310
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
311
+ def prepare_extra_step_kwargs(self, generator, eta):
312
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
313
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
314
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
315
+ # and should be between [0, 1]
316
+
317
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
318
+ extra_step_kwargs = {}
319
+ if accepts_eta:
320
+ extra_step_kwargs["eta"] = eta
321
+
322
+ # check if the scheduler accepts generator
323
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
324
+ if accepts_generator:
325
+ extra_step_kwargs["generator"] = generator
326
+ return extra_step_kwargs
327
+
328
+ def check_inputs(
329
+ self,
330
+ prompt,
331
+ callback_steps,
332
+ negative_prompt=None,
333
+ prompt_embeds=None,
334
+ negative_prompt_embeds=None,
335
+ callback_on_step_end_tensor_inputs=None,
336
+ attention_mask=None,
337
+ negative_attention_mask=None,
338
+ ):
339
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
340
+ raise ValueError(
341
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
342
+ f" {type(callback_steps)}."
343
+ )
344
+
345
+ if callback_on_step_end_tensor_inputs is not None and not all(
346
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
347
+ ):
348
+ raise ValueError(
349
+ 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]}"
350
+ )
351
+
352
+ if prompt is not None and prompt_embeds is not None:
353
+ raise ValueError(
354
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
355
+ " only forward one of the two."
356
+ )
357
+ elif prompt is None and prompt_embeds is None:
358
+ raise ValueError(
359
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
360
+ )
361
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
362
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
363
+
364
+ if negative_prompt is not None and negative_prompt_embeds is not None:
365
+ raise ValueError(
366
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
367
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
368
+ )
369
+
370
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
371
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
372
+ raise ValueError(
373
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
374
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
375
+ f" {negative_prompt_embeds.shape}."
376
+ )
377
+
378
+ if negative_prompt_embeds is not None and negative_attention_mask is None:
379
+ raise ValueError("Please provide `negative_attention_mask` along with `negative_prompt_embeds`")
380
+
381
+ if negative_prompt_embeds is not None and negative_attention_mask is not None:
382
+ if negative_prompt_embeds.shape[:2] != negative_attention_mask.shape:
383
+ raise ValueError(
384
+ "`negative_prompt_embeds` and `negative_attention_mask` must have the same batch_size and token length when passed directly, but"
385
+ f" got: `negative_prompt_embeds` {negative_prompt_embeds.shape[:2]} != `negative_attention_mask`"
386
+ f" {negative_attention_mask.shape}."
387
+ )
388
+
389
+ if prompt_embeds is not None and attention_mask is None:
390
+ raise ValueError("Please provide `attention_mask` along with `prompt_embeds`")
391
+
392
+ if prompt_embeds is not None and attention_mask is not None:
393
+ if prompt_embeds.shape[:2] != attention_mask.shape:
394
+ raise ValueError(
395
+ "`prompt_embeds` and `attention_mask` must have the same batch_size and token length when passed directly, but"
396
+ f" got: `prompt_embeds` {prompt_embeds.shape[:2]} != `attention_mask`"
397
+ f" {attention_mask.shape}."
398
+ )
399
+
400
+ @property
401
+ def guidance_scale(self):
402
+ return self._guidance_scale
403
+
404
+ @property
405
+ def do_classifier_free_guidance(self):
406
+ return self._guidance_scale > 1
407
+
408
+ @property
409
+ def num_timesteps(self):
410
+ return self._num_timesteps
411
+
412
+ @torch.no_grad()
413
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
414
+ def __call__(
415
+ self,
416
+ prompt: Union[str, List[str]] = None,
417
+ image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] = None,
418
+ strength: float = 0.3,
419
+ num_inference_steps: int = 25,
420
+ guidance_scale: float = 3.0,
421
+ negative_prompt: Optional[Union[str, List[str]]] = None,
422
+ num_images_per_prompt: Optional[int] = 1,
423
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
424
+ prompt_embeds: Optional[torch.FloatTensor] = None,
425
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
426
+ attention_mask: Optional[torch.FloatTensor] = None,
427
+ negative_attention_mask: Optional[torch.FloatTensor] = None,
428
+ output_type: Optional[str] = "pil",
429
+ return_dict: bool = True,
430
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
431
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
432
+ **kwargs,
433
+ ):
434
+ """
435
+ Function invoked when calling the pipeline for generation.
436
+
437
+ Args:
438
+ prompt (`str` or `List[str]`, *optional*):
439
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
440
+ instead.
441
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
442
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
443
+ process.
444
+ strength (`float`, *optional*, defaults to 0.8):
445
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
446
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
447
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
448
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
449
+ essentially ignores `image`.
450
+ num_inference_steps (`int`, *optional*, defaults to 50):
451
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
452
+ expense of slower inference.
453
+ guidance_scale (`float`, *optional*, defaults to 3.0):
454
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
455
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
456
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
457
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
458
+ usually at the expense of lower image quality.
459
+ negative_prompt (`str` or `List[str]`, *optional*):
460
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
461
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
462
+ less than `1`).
463
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
464
+ The number of images to generate per prompt.
465
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
466
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
467
+ to make generation deterministic.
468
+ prompt_embeds (`torch.FloatTensor`, *optional*):
469
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
470
+ provided, text embeddings will be generated from `prompt` input argument.
471
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
472
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
473
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
474
+ argument.
475
+ attention_mask (`torch.FloatTensor`, *optional*):
476
+ Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
477
+ negative_attention_mask (`torch.FloatTensor`, *optional*):
478
+ Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
479
+ output_type (`str`, *optional*, defaults to `"pil"`):
480
+ The output format of the generate image. Choose between
481
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
482
+ return_dict (`bool`, *optional*, defaults to `True`):
483
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
484
+ callback_on_step_end (`Callable`, *optional*):
485
+ A function that calls at the end of each denoising steps during the inference. The function is called
486
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
487
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
488
+ `callback_on_step_end_tensor_inputs`.
489
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
490
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
491
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
492
+ `._callback_tensor_inputs` attribute of your pipeline class.
493
+
494
+ Examples:
495
+
496
+ Returns:
497
+ [`~pipelines.ImagePipelineOutput`] or `tuple`
498
+
499
+ """
500
+ callback = kwargs.pop("callback", None)
501
+ callback_steps = kwargs.pop("callback_steps", None)
502
+
503
+ if callback is not None:
504
+ deprecate(
505
+ "callback",
506
+ "1.0.0",
507
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
508
+ )
509
+ if callback_steps is not None:
510
+ deprecate(
511
+ "callback_steps",
512
+ "1.0.0",
513
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
514
+ )
515
+
516
+ if callback_on_step_end_tensor_inputs is not None and not all(
517
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
518
+ ):
519
+ raise ValueError(
520
+ 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]}"
521
+ )
522
+
523
+ cut_context = True
524
+ # 1. Check inputs. Raise error if not correct
525
+ self.check_inputs(
526
+ prompt,
527
+ callback_steps,
528
+ negative_prompt,
529
+ prompt_embeds,
530
+ negative_prompt_embeds,
531
+ callback_on_step_end_tensor_inputs,
532
+ attention_mask,
533
+ negative_attention_mask,
534
+ )
535
+
536
+ self._guidance_scale = guidance_scale
537
+
538
+ if prompt is not None and isinstance(prompt, str):
539
+ batch_size = 1
540
+ elif prompt is not None and isinstance(prompt, list):
541
+ batch_size = len(prompt)
542
+ else:
543
+ batch_size = prompt_embeds.shape[0]
544
+
545
+ device = self._execution_device
546
+
547
+ # 3. Encode input prompt
548
+ prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask = self.encode_prompt(
549
+ prompt,
550
+ self.do_classifier_free_guidance,
551
+ num_images_per_prompt=num_images_per_prompt,
552
+ device=device,
553
+ negative_prompt=negative_prompt,
554
+ prompt_embeds=prompt_embeds,
555
+ negative_prompt_embeds=negative_prompt_embeds,
556
+ _cut_context=cut_context,
557
+ attention_mask=attention_mask,
558
+ negative_attention_mask=negative_attention_mask,
559
+ )
560
+
561
+ if self.do_classifier_free_guidance:
562
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
563
+ attention_mask = torch.cat([negative_attention_mask, attention_mask]).bool()
564
+ if not isinstance(image, list):
565
+ image = [image]
566
+ if not all(isinstance(i, (PIL.Image.Image, torch.Tensor)) for i in image):
567
+ raise ValueError(
568
+ f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support PIL image and pytorch tensor"
569
+ )
570
+
571
+ image = torch.cat([prepare_image(i) for i in image], dim=0)
572
+ image = image.to(dtype=prompt_embeds.dtype, device=device)
573
+ # 4. Prepare timesteps
574
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
575
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
576
+ # 5. Prepare latents
577
+ latents = self.movq.encode(image)["latents"]
578
+ latents = latents.repeat_interleave(num_images_per_prompt, dim=0)
579
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
580
+ latents = self.prepare_latents(
581
+ latents, latent_timestep, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
582
+ )
583
+ if hasattr(self, "text_encoder_offload_hook") and self.text_encoder_offload_hook is not None:
584
+ self.text_encoder_offload_hook.offload()
585
+
586
+ # 7. Denoising loop
587
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
588
+ self._num_timesteps = len(timesteps)
589
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
590
+ for i, t in enumerate(timesteps):
591
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
592
+
593
+ # predict the noise residual
594
+ noise_pred = self.unet(
595
+ latent_model_input,
596
+ t,
597
+ encoder_hidden_states=prompt_embeds,
598
+ encoder_attention_mask=attention_mask,
599
+ )[0]
600
+ if self.do_classifier_free_guidance:
601
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
602
+
603
+ noise_pred = (guidance_scale + 1.0) * noise_pred_text - guidance_scale * noise_pred_uncond
604
+
605
+ # compute the previous noisy sample x_t -> x_t-1
606
+ latents = self.scheduler.step(
607
+ noise_pred,
608
+ t,
609
+ latents,
610
+ generator=generator,
611
+ ).prev_sample
612
+
613
+ if callback_on_step_end is not None:
614
+ callback_kwargs = {}
615
+ for k in callback_on_step_end_tensor_inputs:
616
+ callback_kwargs[k] = locals()[k]
617
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
618
+
619
+ latents = callback_outputs.pop("latents", latents)
620
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
621
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
622
+ attention_mask = callback_outputs.pop("attention_mask", attention_mask)
623
+ negative_attention_mask = callback_outputs.pop("negative_attention_mask", negative_attention_mask)
624
+
625
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
626
+ progress_bar.update()
627
+ if callback is not None and i % callback_steps == 0:
628
+ step_idx = i // getattr(self.scheduler, "order", 1)
629
+ callback(step_idx, t, latents)
630
+
631
+ # post-processing
632
+ if output_type not in ["pt", "np", "pil", "latent"]:
633
+ raise ValueError(
634
+ f"Only the output types `pt`, `pil`, `np` and `latent` are supported not output_type={output_type}"
635
+ )
636
+ if not output_type == "latent":
637
+ image = self.movq.decode(latents, force_not_quantize=True)["sample"]
638
+
639
+ if output_type in ["np", "pil"]:
640
+ image = image * 0.5 + 0.5
641
+ image = image.clamp(0, 1)
642
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
643
+
644
+ if output_type == "pil":
645
+ image = self.numpy_to_pil(image)
646
+ else:
647
+ image = latents
648
+
649
+ self.maybe_free_model_hooks()
650
+
651
+ if not return_dict:
652
+ return (image,)
653
+
654
+ return ImagePipelineOutput(images=image)