diffusers 0.30.3__py3-none-any.whl → 0.32.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. diffusers/__init__.py +97 -4
  2. diffusers/callbacks.py +56 -3
  3. diffusers/configuration_utils.py +13 -1
  4. diffusers/image_processor.py +282 -71
  5. diffusers/loaders/__init__.py +24 -3
  6. diffusers/loaders/ip_adapter.py +543 -16
  7. diffusers/loaders/lora_base.py +138 -125
  8. diffusers/loaders/lora_conversion_utils.py +647 -0
  9. diffusers/loaders/lora_pipeline.py +2216 -230
  10. diffusers/loaders/peft.py +380 -0
  11. diffusers/loaders/single_file_model.py +71 -4
  12. diffusers/loaders/single_file_utils.py +597 -10
  13. diffusers/loaders/textual_inversion.py +5 -3
  14. diffusers/loaders/transformer_flux.py +181 -0
  15. diffusers/loaders/transformer_sd3.py +89 -0
  16. diffusers/loaders/unet.py +56 -12
  17. diffusers/models/__init__.py +49 -12
  18. diffusers/models/activations.py +22 -9
  19. diffusers/models/adapter.py +53 -53
  20. diffusers/models/attention.py +98 -13
  21. diffusers/models/attention_flax.py +1 -1
  22. diffusers/models/attention_processor.py +2160 -346
  23. diffusers/models/autoencoders/__init__.py +5 -0
  24. diffusers/models/autoencoders/autoencoder_dc.py +620 -0
  25. diffusers/models/autoencoders/autoencoder_kl.py +73 -12
  26. diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
  27. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +213 -105
  28. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
  29. diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
  30. diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
  31. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +3 -10
  32. diffusers/models/autoencoders/autoencoder_tiny.py +4 -2
  33. diffusers/models/autoencoders/vae.py +18 -5
  34. diffusers/models/controlnet.py +47 -802
  35. diffusers/models/controlnet_flux.py +70 -0
  36. diffusers/models/controlnet_sd3.py +26 -376
  37. diffusers/models/controlnet_sparsectrl.py +46 -719
  38. diffusers/models/controlnets/__init__.py +23 -0
  39. diffusers/models/controlnets/controlnet.py +872 -0
  40. diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +5 -5
  41. diffusers/models/controlnets/controlnet_flux.py +536 -0
  42. diffusers/models/{controlnet_hunyuan.py → controlnets/controlnet_hunyuan.py} +7 -7
  43. diffusers/models/controlnets/controlnet_sd3.py +489 -0
  44. diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
  45. diffusers/models/controlnets/controlnet_union.py +832 -0
  46. diffusers/models/{controlnet_xs.py → controlnets/controlnet_xs.py} +14 -13
  47. diffusers/models/controlnets/multicontrolnet.py +183 -0
  48. diffusers/models/embeddings.py +996 -92
  49. diffusers/models/embeddings_flax.py +23 -9
  50. diffusers/models/model_loading_utils.py +264 -14
  51. diffusers/models/modeling_flax_utils.py +1 -1
  52. diffusers/models/modeling_utils.py +334 -51
  53. diffusers/models/normalization.py +157 -13
  54. diffusers/models/transformers/__init__.py +6 -0
  55. diffusers/models/transformers/auraflow_transformer_2d.py +3 -2
  56. diffusers/models/transformers/cogvideox_transformer_3d.py +69 -13
  57. diffusers/models/transformers/dit_transformer_2d.py +1 -1
  58. diffusers/models/transformers/latte_transformer_3d.py +4 -4
  59. diffusers/models/transformers/pixart_transformer_2d.py +10 -2
  60. diffusers/models/transformers/sana_transformer.py +488 -0
  61. diffusers/models/transformers/stable_audio_transformer.py +1 -1
  62. diffusers/models/transformers/transformer_2d.py +1 -1
  63. diffusers/models/transformers/transformer_allegro.py +422 -0
  64. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  65. diffusers/models/transformers/transformer_flux.py +189 -51
  66. diffusers/models/transformers/transformer_hunyuan_video.py +789 -0
  67. diffusers/models/transformers/transformer_ltx.py +469 -0
  68. diffusers/models/transformers/transformer_mochi.py +499 -0
  69. diffusers/models/transformers/transformer_sd3.py +112 -18
  70. diffusers/models/transformers/transformer_temporal.py +1 -1
  71. diffusers/models/unets/unet_1d_blocks.py +1 -1
  72. diffusers/models/unets/unet_2d.py +8 -1
  73. diffusers/models/unets/unet_2d_blocks.py +88 -21
  74. diffusers/models/unets/unet_2d_condition.py +9 -9
  75. diffusers/models/unets/unet_3d_blocks.py +9 -7
  76. diffusers/models/unets/unet_motion_model.py +46 -68
  77. diffusers/models/unets/unet_spatio_temporal_condition.py +23 -0
  78. diffusers/models/unets/unet_stable_cascade.py +2 -2
  79. diffusers/models/unets/uvit_2d.py +1 -1
  80. diffusers/models/upsampling.py +14 -6
  81. diffusers/pipelines/__init__.py +69 -6
  82. diffusers/pipelines/allegro/__init__.py +48 -0
  83. diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
  84. diffusers/pipelines/allegro/pipeline_output.py +23 -0
  85. diffusers/pipelines/animatediff/__init__.py +2 -0
  86. diffusers/pipelines/animatediff/pipeline_animatediff.py +45 -21
  87. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +52 -22
  88. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +18 -4
  89. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +3 -1
  90. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +104 -72
  91. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  92. diffusers/pipelines/audioldm2/modeling_audioldm2.py +3 -3
  93. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +2 -9
  94. diffusers/pipelines/auto_pipeline.py +88 -10
  95. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  96. diffusers/pipelines/cogvideo/__init__.py +2 -0
  97. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +80 -39
  98. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +825 -0
  99. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +108 -50
  100. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +89 -50
  101. diffusers/pipelines/cogview3/__init__.py +47 -0
  102. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  103. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  104. diffusers/pipelines/controlnet/__init__.py +86 -80
  105. diffusers/pipelines/controlnet/multicontrolnet.py +7 -178
  106. diffusers/pipelines/controlnet/pipeline_controlnet.py +20 -3
  107. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +9 -2
  108. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +9 -2
  109. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +37 -15
  110. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +12 -4
  111. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +9 -4
  112. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
  113. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
  114. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
  115. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +22 -4
  116. diffusers/pipelines/controlnet_sd3/__init__.py +4 -0
  117. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +56 -20
  118. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  119. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  120. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  121. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +16 -4
  122. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +1 -1
  123. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +32 -9
  124. diffusers/pipelines/flux/__init__.py +23 -1
  125. diffusers/pipelines/flux/modeling_flux.py +47 -0
  126. diffusers/pipelines/flux/pipeline_flux.py +256 -48
  127. diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
  128. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
  129. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
  130. diffusers/pipelines/flux/pipeline_flux_controlnet.py +1006 -0
  131. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +998 -0
  132. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1204 -0
  133. diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
  134. diffusers/pipelines/flux/pipeline_flux_img2img.py +856 -0
  135. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1022 -0
  136. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
  137. diffusers/pipelines/flux/pipeline_output.py +16 -0
  138. diffusers/pipelines/free_noise_utils.py +365 -5
  139. diffusers/pipelines/hunyuan_video/__init__.py +48 -0
  140. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
  141. diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
  142. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +20 -4
  143. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +9 -9
  144. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +2 -2
  145. diffusers/pipelines/kolors/pipeline_kolors.py +1 -1
  146. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +14 -11
  147. diffusers/pipelines/kolors/text_encoder.py +2 -2
  148. diffusers/pipelines/kolors/tokenizer.py +4 -0
  149. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +1 -1
  150. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +1 -1
  151. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  152. diffusers/pipelines/latte/pipeline_latte.py +2 -2
  153. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +15 -3
  154. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +15 -3
  155. diffusers/pipelines/ltx/__init__.py +50 -0
  156. diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
  157. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
  158. diffusers/pipelines/ltx/pipeline_output.py +20 -0
  159. diffusers/pipelines/lumina/pipeline_lumina.py +3 -10
  160. diffusers/pipelines/mochi/__init__.py +48 -0
  161. diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
  162. diffusers/pipelines/mochi/pipeline_output.py +20 -0
  163. diffusers/pipelines/pag/__init__.py +13 -0
  164. diffusers/pipelines/pag/pag_utils.py +8 -2
  165. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +2 -3
  166. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1543 -0
  167. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +3 -5
  168. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1683 -0
  169. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +22 -6
  170. diffusers/pipelines/pag/pipeline_pag_kolors.py +1 -1
  171. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +7 -14
  172. diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
  173. diffusers/pipelines/pag/pipeline_pag_sd.py +18 -6
  174. diffusers/pipelines/pag/pipeline_pag_sd_3.py +18 -9
  175. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
  176. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +5 -1
  177. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1094 -0
  178. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
  179. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +18 -6
  180. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +31 -16
  181. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +42 -19
  182. diffusers/pipelines/pia/pipeline_pia.py +2 -0
  183. diffusers/pipelines/pipeline_flax_utils.py +1 -1
  184. diffusers/pipelines/pipeline_loading_utils.py +250 -31
  185. diffusers/pipelines/pipeline_utils.py +158 -186
  186. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +7 -14
  187. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +7 -14
  188. diffusers/pipelines/sana/__init__.py +47 -0
  189. diffusers/pipelines/sana/pipeline_output.py +21 -0
  190. diffusers/pipelines/sana/pipeline_sana.py +884 -0
  191. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +12 -1
  192. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +35 -3
  193. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +2 -2
  194. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +46 -9
  195. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -1
  196. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +1 -1
  197. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +241 -81
  198. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +228 -23
  199. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +82 -13
  200. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +60 -11
  201. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -1
  202. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  203. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +16 -4
  204. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +16 -4
  205. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -12
  206. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +29 -22
  207. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +29 -22
  208. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +1 -1
  209. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +1 -1
  210. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +16 -4
  211. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +15 -3
  212. diffusers/pipelines/unidiffuser/modeling_uvit.py +2 -2
  213. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  214. diffusers/quantizers/__init__.py +16 -0
  215. diffusers/quantizers/auto.py +139 -0
  216. diffusers/quantizers/base.py +233 -0
  217. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  218. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +561 -0
  219. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  220. diffusers/quantizers/gguf/__init__.py +1 -0
  221. diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
  222. diffusers/quantizers/gguf/utils.py +456 -0
  223. diffusers/quantizers/quantization_config.py +669 -0
  224. diffusers/quantizers/torchao/__init__.py +15 -0
  225. diffusers/quantizers/torchao/torchao_quantizer.py +285 -0
  226. diffusers/schedulers/scheduling_ddim.py +4 -1
  227. diffusers/schedulers/scheduling_ddim_cogvideox.py +4 -1
  228. diffusers/schedulers/scheduling_ddim_parallel.py +4 -1
  229. diffusers/schedulers/scheduling_ddpm.py +6 -7
  230. diffusers/schedulers/scheduling_ddpm_parallel.py +6 -7
  231. diffusers/schedulers/scheduling_deis_multistep.py +102 -6
  232. diffusers/schedulers/scheduling_dpmsolver_multistep.py +113 -6
  233. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +111 -5
  234. diffusers/schedulers/scheduling_dpmsolver_sde.py +125 -10
  235. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +126 -7
  236. diffusers/schedulers/scheduling_edm_euler.py +8 -6
  237. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +4 -1
  238. diffusers/schedulers/scheduling_euler_discrete.py +92 -7
  239. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +153 -6
  240. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +4 -5
  241. diffusers/schedulers/scheduling_heun_discrete.py +114 -8
  242. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +116 -11
  243. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +110 -8
  244. diffusers/schedulers/scheduling_lcm.py +2 -6
  245. diffusers/schedulers/scheduling_lms_discrete.py +76 -1
  246. diffusers/schedulers/scheduling_repaint.py +1 -1
  247. diffusers/schedulers/scheduling_sasolver.py +102 -6
  248. diffusers/schedulers/scheduling_tcd.py +2 -6
  249. diffusers/schedulers/scheduling_unclip.py +4 -1
  250. diffusers/schedulers/scheduling_unipc_multistep.py +127 -5
  251. diffusers/training_utils.py +63 -19
  252. diffusers/utils/__init__.py +7 -1
  253. diffusers/utils/constants.py +1 -0
  254. diffusers/utils/dummy_pt_objects.py +240 -0
  255. diffusers/utils/dummy_torch_and_transformers_objects.py +435 -0
  256. diffusers/utils/dynamic_modules_utils.py +3 -3
  257. diffusers/utils/hub_utils.py +44 -40
  258. diffusers/utils/import_utils.py +98 -8
  259. diffusers/utils/loading_utils.py +28 -4
  260. diffusers/utils/peft_utils.py +6 -3
  261. diffusers/utils/testing_utils.py +115 -1
  262. diffusers/utils/torch_utils.py +3 -0
  263. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/METADATA +73 -72
  264. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/RECORD +268 -193
  265. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/WHEEL +1 -1
  266. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/LICENSE +0 -0
  267. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/entry_points.txt +0 -0
  268. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1627 @@
1
+ # Copyright 2024 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
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from transformers import (
24
+ CLIPImageProcessor,
25
+ CLIPTextModel,
26
+ CLIPTextModelWithProjection,
27
+ CLIPTokenizer,
28
+ CLIPVisionModelWithProjection,
29
+ )
30
+
31
+ from diffusers.utils.import_utils import is_invisible_watermark_available
32
+
33
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
34
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
35
+ from ...loaders import (
36
+ FromSingleFileMixin,
37
+ IPAdapterMixin,
38
+ StableDiffusionXLLoraLoaderMixin,
39
+ TextualInversionLoaderMixin,
40
+ )
41
+ from ...models import AutoencoderKL, ControlNetModel, ControlNetUnionModel, ImageProjection, UNet2DConditionModel
42
+ from ...models.attention_processor import (
43
+ AttnProcessor2_0,
44
+ XFormersAttnProcessor,
45
+ )
46
+ from ...models.lora import adjust_lora_scale_text_encoder
47
+ from ...schedulers import KarrasDiffusionSchedulers
48
+ from ...utils import (
49
+ USE_PEFT_BACKEND,
50
+ deprecate,
51
+ logging,
52
+ replace_example_docstring,
53
+ scale_lora_layers,
54
+ unscale_lora_layers,
55
+ )
56
+ from ...utils.torch_utils import is_compiled_module, randn_tensor
57
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
58
+ from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
59
+
60
+
61
+ if is_invisible_watermark_available():
62
+ from ..stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
63
+
64
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
65
+
66
+
67
+ EXAMPLE_DOC_STRING = """
68
+ Examples:
69
+ ```py
70
+ # !pip install controlnet_aux
71
+ from diffusers import (
72
+ StableDiffusionXLControlNetUnionImg2ImgPipeline,
73
+ ControlNetUnionModel,
74
+ AutoencoderKL,
75
+ )
76
+ from diffusers.utils import load_image
77
+ import torch
78
+ from PIL import Image
79
+ import numpy as np
80
+
81
+ prompt = "A cat"
82
+ # download an image
83
+ image = load_image(
84
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
85
+ )
86
+ # initialize the models and pipeline
87
+ controlnet = ControlNetUnionModel.from_pretrained(
88
+ "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
89
+ )
90
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
91
+ pipe = StableDiffusionXLControlNetUnionImg2ImgPipeline.from_pretrained(
92
+ "stabilityai/stable-diffusion-xl-base-1.0",
93
+ controlnet=controlnet,
94
+ vae=vae,
95
+ torch_dtype=torch.float16,
96
+ variant="fp16",
97
+ ).to("cuda")
98
+ # `enable_model_cpu_offload` is not recommended due to multiple generations
99
+ height = image.height
100
+ width = image.width
101
+ ratio = np.sqrt(1024.0 * 1024.0 / (width * height))
102
+ # 3 * 3 upscale correspond to 16 * 3 multiply, 2 * 2 correspond to 16 * 2 multiply and so on.
103
+ scale_image_factor = 3
104
+ base_factor = 16
105
+ factor = scale_image_factor * base_factor
106
+ W, H = int(width * ratio) // factor * factor, int(height * ratio) // factor * factor
107
+ image = image.resize((W, H))
108
+ target_width = W // scale_image_factor
109
+ target_height = H // scale_image_factor
110
+ images = []
111
+ crops_coords_list = [
112
+ (0, 0),
113
+ (0, width // 2),
114
+ (height // 2, 0),
115
+ (width // 2, height // 2),
116
+ 0,
117
+ 0,
118
+ 0,
119
+ 0,
120
+ 0,
121
+ ]
122
+ for i in range(scale_image_factor):
123
+ for j in range(scale_image_factor):
124
+ left = j * target_width
125
+ top = i * target_height
126
+ right = left + target_width
127
+ bottom = top + target_height
128
+ cropped_image = image.crop((left, top, right, bottom))
129
+ cropped_image = cropped_image.resize((W, H))
130
+ images.append(cropped_image)
131
+ # set ControlNetUnion input
132
+ result_images = []
133
+ for sub_img, crops_coords in zip(images, crops_coords_list):
134
+ new_width, new_height = W, H
135
+ out = pipe(
136
+ prompt=[prompt] * 1,
137
+ image=sub_img,
138
+ control_image=[sub_img],
139
+ control_mode=[6],
140
+ width=new_width,
141
+ height=new_height,
142
+ num_inference_steps=30,
143
+ crops_coords_top_left=(W, H),
144
+ target_size=(W, H),
145
+ original_size=(W * 2, H * 2),
146
+ )
147
+ result_images.append(out.images[0])
148
+ new_im = Image.new("RGB", (new_width * scale_image_factor, new_height * scale_image_factor))
149
+ new_im.paste(result_images[0], (0, 0))
150
+ new_im.paste(result_images[1], (new_width, 0))
151
+ new_im.paste(result_images[2], (new_width * 2, 0))
152
+ new_im.paste(result_images[3], (0, new_height))
153
+ new_im.paste(result_images[4], (new_width, new_height))
154
+ new_im.paste(result_images[5], (new_width * 2, new_height))
155
+ new_im.paste(result_images[6], (0, new_height * 2))
156
+ new_im.paste(result_images[7], (new_width, new_height * 2))
157
+ new_im.paste(result_images[8], (new_width * 2, new_height * 2))
158
+ ```
159
+ """
160
+
161
+
162
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
163
+ def retrieve_latents(
164
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
165
+ ):
166
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
167
+ return encoder_output.latent_dist.sample(generator)
168
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
169
+ return encoder_output.latent_dist.mode()
170
+ elif hasattr(encoder_output, "latents"):
171
+ return encoder_output.latents
172
+ else:
173
+ raise AttributeError("Could not access latents of provided encoder_output")
174
+
175
+
176
+ class StableDiffusionXLControlNetUnionImg2ImgPipeline(
177
+ DiffusionPipeline,
178
+ StableDiffusionMixin,
179
+ TextualInversionLoaderMixin,
180
+ StableDiffusionXLLoraLoaderMixin,
181
+ FromSingleFileMixin,
182
+ IPAdapterMixin,
183
+ ):
184
+ r"""
185
+ Pipeline for image-to-image generation using Stable Diffusion XL with ControlNet guidance.
186
+
187
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
188
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
189
+
190
+ The pipeline also inherits the following loading methods:
191
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
192
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
193
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
194
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
195
+
196
+ Args:
197
+ vae ([`AutoencoderKL`]):
198
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
199
+ text_encoder ([`CLIPTextModel`]):
200
+ Frozen text-encoder. Stable Diffusion uses the text portion of
201
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
202
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
203
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
204
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
205
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
206
+ specifically the
207
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
208
+ variant.
209
+ tokenizer (`CLIPTokenizer`):
210
+ Tokenizer of class
211
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
212
+ tokenizer_2 (`CLIPTokenizer`):
213
+ Second Tokenizer of class
214
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
215
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
216
+ controlnet ([`ControlNetUnionModel`]):
217
+ Provides additional conditioning to the unet during the denoising process.
218
+ scheduler ([`SchedulerMixin`]):
219
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
220
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
221
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
222
+ Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
223
+ config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
224
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
225
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
226
+ `stabilityai/stable-diffusion-xl-base-1-0`.
227
+ add_watermarker (`bool`, *optional*):
228
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
229
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
230
+ watermarker will be used.
231
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
232
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
233
+ """
234
+
235
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
236
+ _optional_components = [
237
+ "tokenizer",
238
+ "tokenizer_2",
239
+ "text_encoder",
240
+ "text_encoder_2",
241
+ "feature_extractor",
242
+ "image_encoder",
243
+ ]
244
+ _callback_tensor_inputs = [
245
+ "latents",
246
+ "prompt_embeds",
247
+ "add_text_embeds",
248
+ "add_time_ids",
249
+ ]
250
+
251
+ def __init__(
252
+ self,
253
+ vae: AutoencoderKL,
254
+ text_encoder: CLIPTextModel,
255
+ text_encoder_2: CLIPTextModelWithProjection,
256
+ tokenizer: CLIPTokenizer,
257
+ tokenizer_2: CLIPTokenizer,
258
+ unet: UNet2DConditionModel,
259
+ controlnet: ControlNetUnionModel,
260
+ scheduler: KarrasDiffusionSchedulers,
261
+ requires_aesthetics_score: bool = False,
262
+ force_zeros_for_empty_prompt: bool = True,
263
+ add_watermarker: Optional[bool] = None,
264
+ feature_extractor: CLIPImageProcessor = None,
265
+ image_encoder: CLIPVisionModelWithProjection = None,
266
+ ):
267
+ super().__init__()
268
+
269
+ if not isinstance(controlnet, ControlNetUnionModel):
270
+ raise ValueError("Expected `controlnet` to be of type `ControlNetUnionModel`.")
271
+
272
+ self.register_modules(
273
+ vae=vae,
274
+ text_encoder=text_encoder,
275
+ text_encoder_2=text_encoder_2,
276
+ tokenizer=tokenizer,
277
+ tokenizer_2=tokenizer_2,
278
+ unet=unet,
279
+ controlnet=controlnet,
280
+ scheduler=scheduler,
281
+ feature_extractor=feature_extractor,
282
+ image_encoder=image_encoder,
283
+ )
284
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
285
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
286
+ self.control_image_processor = VaeImageProcessor(
287
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
288
+ )
289
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
290
+
291
+ if add_watermarker:
292
+ self.watermark = StableDiffusionXLWatermarker()
293
+ else:
294
+ self.watermark = None
295
+
296
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
297
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
298
+
299
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
300
+ def encode_prompt(
301
+ self,
302
+ prompt: str,
303
+ prompt_2: Optional[str] = None,
304
+ device: Optional[torch.device] = None,
305
+ num_images_per_prompt: int = 1,
306
+ do_classifier_free_guidance: bool = True,
307
+ negative_prompt: Optional[str] = None,
308
+ negative_prompt_2: Optional[str] = None,
309
+ prompt_embeds: Optional[torch.Tensor] = None,
310
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
311
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
312
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
313
+ lora_scale: Optional[float] = None,
314
+ clip_skip: Optional[int] = None,
315
+ ):
316
+ r"""
317
+ Encodes the prompt into text encoder hidden states.
318
+
319
+ Args:
320
+ prompt (`str` or `List[str]`, *optional*):
321
+ prompt to be encoded
322
+ prompt_2 (`str` or `List[str]`, *optional*):
323
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
324
+ used in both text-encoders
325
+ device: (`torch.device`):
326
+ torch device
327
+ num_images_per_prompt (`int`):
328
+ number of images that should be generated per prompt
329
+ do_classifier_free_guidance (`bool`):
330
+ whether to use classifier free guidance or not
331
+ negative_prompt (`str` or `List[str]`, *optional*):
332
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
333
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
334
+ less than `1`).
335
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
336
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
337
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
338
+ prompt_embeds (`torch.Tensor`, *optional*):
339
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
340
+ provided, text embeddings will be generated from `prompt` input argument.
341
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
342
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
343
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
344
+ argument.
345
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
346
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
347
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
348
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
349
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
350
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
351
+ input argument.
352
+ lora_scale (`float`, *optional*):
353
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
354
+ clip_skip (`int`, *optional*):
355
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
356
+ the output of the pre-final layer will be used for computing the prompt embeddings.
357
+ """
358
+ device = device or self._execution_device
359
+
360
+ # set lora scale so that monkey patched LoRA
361
+ # function of text encoder can correctly access it
362
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
363
+ self._lora_scale = lora_scale
364
+
365
+ # dynamically adjust the LoRA scale
366
+ if self.text_encoder is not None:
367
+ if not USE_PEFT_BACKEND:
368
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
369
+ else:
370
+ scale_lora_layers(self.text_encoder, lora_scale)
371
+
372
+ if self.text_encoder_2 is not None:
373
+ if not USE_PEFT_BACKEND:
374
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
375
+ else:
376
+ scale_lora_layers(self.text_encoder_2, lora_scale)
377
+
378
+ prompt = [prompt] if isinstance(prompt, str) else prompt
379
+
380
+ if prompt is not None:
381
+ batch_size = len(prompt)
382
+ else:
383
+ batch_size = prompt_embeds.shape[0]
384
+
385
+ # Define tokenizers and text encoders
386
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
387
+ text_encoders = (
388
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
389
+ )
390
+
391
+ if prompt_embeds is None:
392
+ prompt_2 = prompt_2 or prompt
393
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
394
+
395
+ # textual inversion: process multi-vector tokens if necessary
396
+ prompt_embeds_list = []
397
+ prompts = [prompt, prompt_2]
398
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
399
+ if isinstance(self, TextualInversionLoaderMixin):
400
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
401
+
402
+ text_inputs = tokenizer(
403
+ prompt,
404
+ padding="max_length",
405
+ max_length=tokenizer.model_max_length,
406
+ truncation=True,
407
+ return_tensors="pt",
408
+ )
409
+
410
+ text_input_ids = text_inputs.input_ids
411
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
412
+
413
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
414
+ text_input_ids, untruncated_ids
415
+ ):
416
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
417
+ logger.warning(
418
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
419
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
420
+ )
421
+
422
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
423
+
424
+ # We are only ALWAYS interested in the pooled output of the final text encoder
425
+ pooled_prompt_embeds = prompt_embeds[0]
426
+ if clip_skip is None:
427
+ prompt_embeds = prompt_embeds.hidden_states[-2]
428
+ else:
429
+ # "2" because SDXL always indexes from the penultimate layer.
430
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
431
+
432
+ prompt_embeds_list.append(prompt_embeds)
433
+
434
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
435
+
436
+ # get unconditional embeddings for classifier free guidance
437
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
438
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
439
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
440
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
441
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
442
+ negative_prompt = negative_prompt or ""
443
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
444
+
445
+ # normalize str to list
446
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
447
+ negative_prompt_2 = (
448
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
449
+ )
450
+
451
+ uncond_tokens: List[str]
452
+ if prompt is not None and type(prompt) is not type(negative_prompt):
453
+ raise TypeError(
454
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
455
+ f" {type(prompt)}."
456
+ )
457
+ elif batch_size != len(negative_prompt):
458
+ raise ValueError(
459
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
460
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
461
+ " the batch size of `prompt`."
462
+ )
463
+ else:
464
+ uncond_tokens = [negative_prompt, negative_prompt_2]
465
+
466
+ negative_prompt_embeds_list = []
467
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
468
+ if isinstance(self, TextualInversionLoaderMixin):
469
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
470
+
471
+ max_length = prompt_embeds.shape[1]
472
+ uncond_input = tokenizer(
473
+ negative_prompt,
474
+ padding="max_length",
475
+ max_length=max_length,
476
+ truncation=True,
477
+ return_tensors="pt",
478
+ )
479
+
480
+ negative_prompt_embeds = text_encoder(
481
+ uncond_input.input_ids.to(device),
482
+ output_hidden_states=True,
483
+ )
484
+ # We are only ALWAYS interested in the pooled output of the final text encoder
485
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
486
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
487
+
488
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
489
+
490
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
491
+
492
+ if self.text_encoder_2 is not None:
493
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
494
+ else:
495
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
496
+
497
+ bs_embed, seq_len, _ = prompt_embeds.shape
498
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
499
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
500
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
501
+
502
+ if do_classifier_free_guidance:
503
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
504
+ seq_len = negative_prompt_embeds.shape[1]
505
+
506
+ if self.text_encoder_2 is not None:
507
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
508
+ else:
509
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
510
+
511
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
512
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
513
+
514
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
515
+ bs_embed * num_images_per_prompt, -1
516
+ )
517
+ if do_classifier_free_guidance:
518
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
519
+ bs_embed * num_images_per_prompt, -1
520
+ )
521
+
522
+ if self.text_encoder is not None:
523
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
524
+ # Retrieve the original scale by scaling back the LoRA layers
525
+ unscale_lora_layers(self.text_encoder, lora_scale)
526
+
527
+ if self.text_encoder_2 is not None:
528
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
529
+ # Retrieve the original scale by scaling back the LoRA layers
530
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
531
+
532
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
533
+
534
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
535
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
536
+ dtype = next(self.image_encoder.parameters()).dtype
537
+
538
+ if not isinstance(image, torch.Tensor):
539
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
540
+
541
+ image = image.to(device=device, dtype=dtype)
542
+ if output_hidden_states:
543
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
544
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
545
+ uncond_image_enc_hidden_states = self.image_encoder(
546
+ torch.zeros_like(image), output_hidden_states=True
547
+ ).hidden_states[-2]
548
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
549
+ num_images_per_prompt, dim=0
550
+ )
551
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
552
+ else:
553
+ image_embeds = self.image_encoder(image).image_embeds
554
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
555
+ uncond_image_embeds = torch.zeros_like(image_embeds)
556
+
557
+ return image_embeds, uncond_image_embeds
558
+
559
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
560
+ def prepare_ip_adapter_image_embeds(
561
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
562
+ ):
563
+ image_embeds = []
564
+ if do_classifier_free_guidance:
565
+ negative_image_embeds = []
566
+ if ip_adapter_image_embeds is None:
567
+ if not isinstance(ip_adapter_image, list):
568
+ ip_adapter_image = [ip_adapter_image]
569
+
570
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
571
+ raise ValueError(
572
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
573
+ )
574
+
575
+ for single_ip_adapter_image, image_proj_layer in zip(
576
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
577
+ ):
578
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
579
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
580
+ single_ip_adapter_image, device, 1, output_hidden_state
581
+ )
582
+
583
+ image_embeds.append(single_image_embeds[None, :])
584
+ if do_classifier_free_guidance:
585
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
586
+ else:
587
+ for single_image_embeds in ip_adapter_image_embeds:
588
+ if do_classifier_free_guidance:
589
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
590
+ negative_image_embeds.append(single_negative_image_embeds)
591
+ image_embeds.append(single_image_embeds)
592
+
593
+ ip_adapter_image_embeds = []
594
+ for i, single_image_embeds in enumerate(image_embeds):
595
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
596
+ if do_classifier_free_guidance:
597
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
598
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
599
+
600
+ single_image_embeds = single_image_embeds.to(device=device)
601
+ ip_adapter_image_embeds.append(single_image_embeds)
602
+
603
+ return ip_adapter_image_embeds
604
+
605
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
606
+ def prepare_extra_step_kwargs(self, generator, eta):
607
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
608
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
609
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
610
+ # and should be between [0, 1]
611
+
612
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
613
+ extra_step_kwargs = {}
614
+ if accepts_eta:
615
+ extra_step_kwargs["eta"] = eta
616
+
617
+ # check if the scheduler accepts generator
618
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
619
+ if accepts_generator:
620
+ extra_step_kwargs["generator"] = generator
621
+ return extra_step_kwargs
622
+
623
+ def check_inputs(
624
+ self,
625
+ prompt,
626
+ prompt_2,
627
+ image,
628
+ strength,
629
+ num_inference_steps,
630
+ callback_steps,
631
+ negative_prompt=None,
632
+ negative_prompt_2=None,
633
+ prompt_embeds=None,
634
+ negative_prompt_embeds=None,
635
+ pooled_prompt_embeds=None,
636
+ negative_pooled_prompt_embeds=None,
637
+ ip_adapter_image=None,
638
+ ip_adapter_image_embeds=None,
639
+ controlnet_conditioning_scale=1.0,
640
+ control_guidance_start=0.0,
641
+ control_guidance_end=1.0,
642
+ callback_on_step_end_tensor_inputs=None,
643
+ ):
644
+ if strength < 0 or strength > 1:
645
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
646
+ if num_inference_steps is None:
647
+ raise ValueError("`num_inference_steps` cannot be None.")
648
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
649
+ raise ValueError(
650
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
651
+ f" {type(num_inference_steps)}."
652
+ )
653
+
654
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
655
+ raise ValueError(
656
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
657
+ f" {type(callback_steps)}."
658
+ )
659
+
660
+ if callback_on_step_end_tensor_inputs is not None and not all(
661
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
662
+ ):
663
+ raise ValueError(
664
+ 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]}"
665
+ )
666
+
667
+ if prompt is not None and prompt_embeds is not None:
668
+ raise ValueError(
669
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
670
+ " only forward one of the two."
671
+ )
672
+ elif prompt_2 is not None and prompt_embeds is not None:
673
+ raise ValueError(
674
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
675
+ " only forward one of the two."
676
+ )
677
+ elif prompt is None and prompt_embeds is None:
678
+ raise ValueError(
679
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
680
+ )
681
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
682
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
683
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
684
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
685
+
686
+ if negative_prompt is not None and negative_prompt_embeds is not None:
687
+ raise ValueError(
688
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
689
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
690
+ )
691
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
692
+ raise ValueError(
693
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
694
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
695
+ )
696
+
697
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
698
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
699
+ raise ValueError(
700
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
701
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
702
+ f" {negative_prompt_embeds.shape}."
703
+ )
704
+
705
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
706
+ raise ValueError(
707
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
708
+ )
709
+
710
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
711
+ raise ValueError(
712
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
713
+ )
714
+
715
+ # Check `image`
716
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
717
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
718
+ )
719
+ if (
720
+ isinstance(self.controlnet, ControlNetModel)
721
+ or is_compiled
722
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
723
+ ):
724
+ self.check_image(image, prompt, prompt_embeds)
725
+ elif (
726
+ isinstance(self.controlnet, ControlNetUnionModel)
727
+ or is_compiled
728
+ and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
729
+ ):
730
+ self.check_image(image, prompt, prompt_embeds)
731
+ else:
732
+ assert False
733
+
734
+ # Check `controlnet_conditioning_scale`
735
+ if (
736
+ isinstance(self.controlnet, ControlNetModel)
737
+ or is_compiled
738
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
739
+ ):
740
+ if not isinstance(controlnet_conditioning_scale, float):
741
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
742
+
743
+ elif (
744
+ isinstance(self.controlnet, ControlNetUnionModel)
745
+ or is_compiled
746
+ and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
747
+ ):
748
+ if not isinstance(controlnet_conditioning_scale, float):
749
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
750
+
751
+ else:
752
+ assert False
753
+
754
+ if not isinstance(control_guidance_start, (tuple, list)):
755
+ control_guidance_start = [control_guidance_start]
756
+
757
+ if not isinstance(control_guidance_end, (tuple, list)):
758
+ control_guidance_end = [control_guidance_end]
759
+
760
+ if len(control_guidance_start) != len(control_guidance_end):
761
+ raise ValueError(
762
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
763
+ )
764
+
765
+ for start, end in zip(control_guidance_start, control_guidance_end):
766
+ if start >= end:
767
+ raise ValueError(
768
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
769
+ )
770
+ if start < 0.0:
771
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
772
+ if end > 1.0:
773
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
774
+
775
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
776
+ raise ValueError(
777
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
778
+ )
779
+
780
+ if ip_adapter_image_embeds is not None:
781
+ if not isinstance(ip_adapter_image_embeds, list):
782
+ raise ValueError(
783
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
784
+ )
785
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
786
+ raise ValueError(
787
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
788
+ )
789
+
790
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.check_image
791
+ def check_image(self, image, prompt, prompt_embeds):
792
+ image_is_pil = isinstance(image, PIL.Image.Image)
793
+ image_is_tensor = isinstance(image, torch.Tensor)
794
+ image_is_np = isinstance(image, np.ndarray)
795
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
796
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
797
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
798
+
799
+ if (
800
+ not image_is_pil
801
+ and not image_is_tensor
802
+ and not image_is_np
803
+ and not image_is_pil_list
804
+ and not image_is_tensor_list
805
+ and not image_is_np_list
806
+ ):
807
+ raise TypeError(
808
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
809
+ )
810
+
811
+ if image_is_pil:
812
+ image_batch_size = 1
813
+ else:
814
+ image_batch_size = len(image)
815
+
816
+ if prompt is not None and isinstance(prompt, str):
817
+ prompt_batch_size = 1
818
+ elif prompt is not None and isinstance(prompt, list):
819
+ prompt_batch_size = len(prompt)
820
+ elif prompt_embeds is not None:
821
+ prompt_batch_size = prompt_embeds.shape[0]
822
+
823
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
824
+ raise ValueError(
825
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
826
+ )
827
+
828
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.prepare_image
829
+ def prepare_control_image(
830
+ self,
831
+ image,
832
+ width,
833
+ height,
834
+ batch_size,
835
+ num_images_per_prompt,
836
+ device,
837
+ dtype,
838
+ do_classifier_free_guidance=False,
839
+ guess_mode=False,
840
+ ):
841
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
842
+ image_batch_size = image.shape[0]
843
+
844
+ if image_batch_size == 1:
845
+ repeat_by = batch_size
846
+ else:
847
+ # image batch size is the same as prompt batch size
848
+ repeat_by = num_images_per_prompt
849
+
850
+ image = image.repeat_interleave(repeat_by, dim=0)
851
+
852
+ image = image.to(device=device, dtype=dtype)
853
+
854
+ if do_classifier_free_guidance and not guess_mode:
855
+ image = torch.cat([image] * 2)
856
+
857
+ return image
858
+
859
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
860
+ def get_timesteps(self, num_inference_steps, strength, device):
861
+ # get the original timestep using init_timestep
862
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
863
+
864
+ t_start = max(num_inference_steps - init_timestep, 0)
865
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
866
+ if hasattr(self.scheduler, "set_begin_index"):
867
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
868
+
869
+ return timesteps, num_inference_steps - t_start
870
+
871
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.prepare_latents
872
+ def prepare_latents(
873
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
874
+ ):
875
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
876
+ raise ValueError(
877
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
878
+ )
879
+
880
+ latents_mean = latents_std = None
881
+ if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
882
+ latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
883
+ if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
884
+ latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
885
+
886
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
887
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
888
+ self.text_encoder_2.to("cpu")
889
+ torch.cuda.empty_cache()
890
+
891
+ image = image.to(device=device, dtype=dtype)
892
+
893
+ batch_size = batch_size * num_images_per_prompt
894
+
895
+ if image.shape[1] == 4:
896
+ init_latents = image
897
+
898
+ else:
899
+ # make sure the VAE is in float32 mode, as it overflows in float16
900
+ if self.vae.config.force_upcast:
901
+ image = image.float()
902
+ self.vae.to(dtype=torch.float32)
903
+
904
+ if isinstance(generator, list) and len(generator) != batch_size:
905
+ raise ValueError(
906
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
907
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
908
+ )
909
+
910
+ elif isinstance(generator, list):
911
+ if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
912
+ image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
913
+ elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
914
+ raise ValueError(
915
+ f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
916
+ )
917
+
918
+ init_latents = [
919
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
920
+ for i in range(batch_size)
921
+ ]
922
+ init_latents = torch.cat(init_latents, dim=0)
923
+ else:
924
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
925
+
926
+ if self.vae.config.force_upcast:
927
+ self.vae.to(dtype)
928
+
929
+ init_latents = init_latents.to(dtype)
930
+ if latents_mean is not None and latents_std is not None:
931
+ latents_mean = latents_mean.to(device=device, dtype=dtype)
932
+ latents_std = latents_std.to(device=device, dtype=dtype)
933
+ init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
934
+ else:
935
+ init_latents = self.vae.config.scaling_factor * init_latents
936
+
937
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
938
+ # expand init_latents for batch_size
939
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
940
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
941
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
942
+ raise ValueError(
943
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
944
+ )
945
+ else:
946
+ init_latents = torch.cat([init_latents], dim=0)
947
+
948
+ if add_noise:
949
+ shape = init_latents.shape
950
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
951
+ # get latents
952
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
953
+
954
+ latents = init_latents
955
+
956
+ return latents
957
+
958
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline._get_add_time_ids
959
+ def _get_add_time_ids(
960
+ self,
961
+ original_size,
962
+ crops_coords_top_left,
963
+ target_size,
964
+ aesthetic_score,
965
+ negative_aesthetic_score,
966
+ negative_original_size,
967
+ negative_crops_coords_top_left,
968
+ negative_target_size,
969
+ dtype,
970
+ text_encoder_projection_dim=None,
971
+ ):
972
+ if self.config.requires_aesthetics_score:
973
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
974
+ add_neg_time_ids = list(
975
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
976
+ )
977
+ else:
978
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
979
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
980
+
981
+ passed_add_embed_dim = (
982
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
983
+ )
984
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
985
+
986
+ if (
987
+ expected_add_embed_dim > passed_add_embed_dim
988
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
989
+ ):
990
+ raise ValueError(
991
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
992
+ )
993
+ elif (
994
+ expected_add_embed_dim < passed_add_embed_dim
995
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
996
+ ):
997
+ raise ValueError(
998
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
999
+ )
1000
+ elif expected_add_embed_dim != passed_add_embed_dim:
1001
+ raise ValueError(
1002
+ 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`."
1003
+ )
1004
+
1005
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
1006
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
1007
+
1008
+ return add_time_ids, add_neg_time_ids
1009
+
1010
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
1011
+ def upcast_vae(self):
1012
+ dtype = self.vae.dtype
1013
+ self.vae.to(dtype=torch.float32)
1014
+ use_torch_2_0_or_xformers = isinstance(
1015
+ self.vae.decoder.mid_block.attentions[0].processor,
1016
+ (
1017
+ AttnProcessor2_0,
1018
+ XFormersAttnProcessor,
1019
+ ),
1020
+ )
1021
+ # if xformers or torch_2_0 is used attention block does not need
1022
+ # to be in float32 which can save lots of memory
1023
+ if use_torch_2_0_or_xformers:
1024
+ self.vae.post_quant_conv.to(dtype)
1025
+ self.vae.decoder.conv_in.to(dtype)
1026
+ self.vae.decoder.mid_block.to(dtype)
1027
+
1028
+ @property
1029
+ def guidance_scale(self):
1030
+ return self._guidance_scale
1031
+
1032
+ @property
1033
+ def clip_skip(self):
1034
+ return self._clip_skip
1035
+
1036
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1037
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1038
+ # corresponds to doing no classifier free guidance.
1039
+ @property
1040
+ def do_classifier_free_guidance(self):
1041
+ return self._guidance_scale > 1
1042
+
1043
+ @property
1044
+ def cross_attention_kwargs(self):
1045
+ return self._cross_attention_kwargs
1046
+
1047
+ @property
1048
+ def num_timesteps(self):
1049
+ return self._num_timesteps
1050
+
1051
+ @property
1052
+ def interrupt(self):
1053
+ return self._interrupt
1054
+
1055
+ @torch.no_grad()
1056
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1057
+ def __call__(
1058
+ self,
1059
+ prompt: Union[str, List[str]] = None,
1060
+ prompt_2: Optional[Union[str, List[str]]] = None,
1061
+ image: PipelineImageInput = None,
1062
+ control_image: PipelineImageInput = None,
1063
+ height: Optional[int] = None,
1064
+ width: Optional[int] = None,
1065
+ strength: float = 0.8,
1066
+ num_inference_steps: int = 50,
1067
+ guidance_scale: float = 5.0,
1068
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1069
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1070
+ num_images_per_prompt: Optional[int] = 1,
1071
+ eta: float = 0.0,
1072
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1073
+ latents: Optional[torch.Tensor] = None,
1074
+ prompt_embeds: Optional[torch.Tensor] = None,
1075
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1076
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1077
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1078
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1079
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1080
+ output_type: Optional[str] = "pil",
1081
+ return_dict: bool = True,
1082
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1083
+ controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
1084
+ guess_mode: bool = False,
1085
+ control_guidance_start: Union[float, List[float]] = 0.0,
1086
+ control_guidance_end: Union[float, List[float]] = 1.0,
1087
+ control_mode: Optional[Union[int, List[int]]] = None,
1088
+ original_size: Tuple[int, int] = None,
1089
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1090
+ target_size: Tuple[int, int] = None,
1091
+ negative_original_size: Optional[Tuple[int, int]] = None,
1092
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1093
+ negative_target_size: Optional[Tuple[int, int]] = None,
1094
+ aesthetic_score: float = 6.0,
1095
+ negative_aesthetic_score: float = 2.5,
1096
+ clip_skip: Optional[int] = None,
1097
+ callback_on_step_end: Optional[
1098
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1099
+ ] = None,
1100
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1101
+ **kwargs,
1102
+ ):
1103
+ r"""
1104
+ Function invoked when calling the pipeline for generation.
1105
+
1106
+ Args:
1107
+ prompt (`str` or `List[str]`, *optional*):
1108
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1109
+ instead.
1110
+ prompt_2 (`str` or `List[str]`, *optional*):
1111
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1112
+ used in both text-encoders
1113
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
1114
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
1115
+ The initial image will be used as the starting point for the image generation process. Can also accept
1116
+ image latents as `image`, if passing latents directly, it will not be encoded again.
1117
+ control_image (`PipelineImageInput`):
1118
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
1119
+ the type is specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also
1120
+ be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
1121
+ and/or width are passed, `image` is resized according to them. If multiple ControlNets are specified in
1122
+ init, images must be passed as a list such that each element of the list can be correctly batched for
1123
+ input to a single controlnet.
1124
+ height (`int`, *optional*, defaults to the size of control_image):
1125
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
1126
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1127
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1128
+ width (`int`, *optional*, defaults to the size of control_image):
1129
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
1130
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1131
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1132
+ strength (`float`, *optional*, defaults to 0.8):
1133
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
1134
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
1135
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
1136
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
1137
+ essentially ignores `image`.
1138
+ num_inference_steps (`int`, *optional*, defaults to 50):
1139
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1140
+ expense of slower inference.
1141
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1142
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1143
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1144
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1145
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1146
+ usually at the expense of lower image quality.
1147
+ negative_prompt (`str` or `List[str]`, *optional*):
1148
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1149
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1150
+ less than `1`).
1151
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1152
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1153
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1154
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1155
+ The number of images to generate per prompt.
1156
+ eta (`float`, *optional*, defaults to 0.0):
1157
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1158
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1159
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1160
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1161
+ to make generation deterministic.
1162
+ latents (`torch.Tensor`, *optional*):
1163
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1164
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1165
+ tensor will ge generated by sampling using the supplied random `generator`.
1166
+ prompt_embeds (`torch.Tensor`, *optional*):
1167
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1168
+ provided, text embeddings will be generated from `prompt` input argument.
1169
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1170
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1171
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1172
+ argument.
1173
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1174
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1175
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1176
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1177
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1178
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1179
+ input argument.
1180
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1181
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1182
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1183
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1184
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1185
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1186
+ output_type (`str`, *optional*, defaults to `"pil"`):
1187
+ The output format of the generate image. Choose between
1188
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1189
+ return_dict (`bool`, *optional*, defaults to `True`):
1190
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1191
+ plain tuple.
1192
+ cross_attention_kwargs (`dict`, *optional*):
1193
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1194
+ `self.processor` in
1195
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1196
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1197
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
1198
+ to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
1199
+ corresponding scale as a list.
1200
+ guess_mode (`bool`, *optional*, defaults to `False`):
1201
+ In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
1202
+ you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
1203
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
1204
+ The percentage of total steps at which the controlnet starts applying.
1205
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
1206
+ The percentage of total steps at which the controlnet stops applying.
1207
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1208
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1209
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1210
+ explained in section 2.2 of
1211
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1212
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1213
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1214
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1215
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1216
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1217
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1218
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1219
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1220
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1221
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1222
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1223
+ micro-conditioning as explained in section 2.2 of
1224
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1225
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1226
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1227
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1228
+ micro-conditioning as explained in section 2.2 of
1229
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1230
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1231
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1232
+ To negatively condition the generation process based on a target image resolution. It should be as same
1233
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1234
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1235
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1236
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1237
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1238
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1239
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1240
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1241
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1242
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1243
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1244
+ clip_skip (`int`, *optional*):
1245
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1246
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1247
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1248
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1249
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1250
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1251
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1252
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1253
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1254
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1255
+ `._callback_tensor_inputs` attribute of your pipeline class.
1256
+
1257
+ Examples:
1258
+
1259
+ Returns:
1260
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1261
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple`
1262
+ containing the output images.
1263
+ """
1264
+
1265
+ callback = kwargs.pop("callback", None)
1266
+ callback_steps = kwargs.pop("callback_steps", None)
1267
+
1268
+ if callback is not None:
1269
+ deprecate(
1270
+ "callback",
1271
+ "1.0.0",
1272
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1273
+ )
1274
+ if callback_steps is not None:
1275
+ deprecate(
1276
+ "callback_steps",
1277
+ "1.0.0",
1278
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1279
+ )
1280
+
1281
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1282
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1283
+
1284
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1285
+
1286
+ # align format for control guidance
1287
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1288
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1289
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1290
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1291
+
1292
+ if not isinstance(control_image, list):
1293
+ control_image = [control_image]
1294
+
1295
+ if not isinstance(control_mode, list):
1296
+ control_mode = [control_mode]
1297
+
1298
+ if len(control_image) != len(control_mode):
1299
+ raise ValueError("Expected len(control_image) == len(control_type)")
1300
+
1301
+ num_control_type = controlnet.config.num_control_type
1302
+
1303
+ # 1. Check inputs
1304
+ control_type = [0 for _ in range(num_control_type)]
1305
+ for _image, control_idx in zip(control_image, control_mode):
1306
+ control_type[control_idx] = 1
1307
+ self.check_inputs(
1308
+ prompt,
1309
+ prompt_2,
1310
+ _image,
1311
+ strength,
1312
+ num_inference_steps,
1313
+ callback_steps,
1314
+ negative_prompt,
1315
+ negative_prompt_2,
1316
+ prompt_embeds,
1317
+ negative_prompt_embeds,
1318
+ pooled_prompt_embeds,
1319
+ negative_pooled_prompt_embeds,
1320
+ ip_adapter_image,
1321
+ ip_adapter_image_embeds,
1322
+ controlnet_conditioning_scale,
1323
+ control_guidance_start,
1324
+ control_guidance_end,
1325
+ callback_on_step_end_tensor_inputs,
1326
+ )
1327
+
1328
+ control_type = torch.Tensor(control_type)
1329
+
1330
+ self._guidance_scale = guidance_scale
1331
+ self._clip_skip = clip_skip
1332
+ self._cross_attention_kwargs = cross_attention_kwargs
1333
+ self._interrupt = False
1334
+
1335
+ # 2. Define call parameters
1336
+ if prompt is not None and isinstance(prompt, str):
1337
+ batch_size = 1
1338
+ elif prompt is not None and isinstance(prompt, list):
1339
+ batch_size = len(prompt)
1340
+ else:
1341
+ batch_size = prompt_embeds.shape[0]
1342
+
1343
+ device = self._execution_device
1344
+
1345
+ global_pool_conditions = controlnet.config.global_pool_conditions
1346
+ guess_mode = guess_mode or global_pool_conditions
1347
+
1348
+ # 3.1. Encode input prompt
1349
+ text_encoder_lora_scale = (
1350
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1351
+ )
1352
+ (
1353
+ prompt_embeds,
1354
+ negative_prompt_embeds,
1355
+ pooled_prompt_embeds,
1356
+ negative_pooled_prompt_embeds,
1357
+ ) = self.encode_prompt(
1358
+ prompt,
1359
+ prompt_2,
1360
+ device,
1361
+ num_images_per_prompt,
1362
+ self.do_classifier_free_guidance,
1363
+ negative_prompt,
1364
+ negative_prompt_2,
1365
+ prompt_embeds=prompt_embeds,
1366
+ negative_prompt_embeds=negative_prompt_embeds,
1367
+ pooled_prompt_embeds=pooled_prompt_embeds,
1368
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1369
+ lora_scale=text_encoder_lora_scale,
1370
+ clip_skip=self.clip_skip,
1371
+ )
1372
+
1373
+ # 3.2 Encode ip_adapter_image
1374
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1375
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1376
+ ip_adapter_image,
1377
+ ip_adapter_image_embeds,
1378
+ device,
1379
+ batch_size * num_images_per_prompt,
1380
+ self.do_classifier_free_guidance,
1381
+ )
1382
+
1383
+ # 4. Prepare image and controlnet_conditioning_image
1384
+ image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
1385
+
1386
+ for idx, _ in enumerate(control_image):
1387
+ control_image[idx] = self.prepare_control_image(
1388
+ image=control_image[idx],
1389
+ width=width,
1390
+ height=height,
1391
+ batch_size=batch_size * num_images_per_prompt,
1392
+ num_images_per_prompt=num_images_per_prompt,
1393
+ device=device,
1394
+ dtype=controlnet.dtype,
1395
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1396
+ guess_mode=guess_mode,
1397
+ )
1398
+ height, width = control_image[idx].shape[-2:]
1399
+
1400
+ # 5. Prepare timesteps
1401
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1402
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
1403
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1404
+ self._num_timesteps = len(timesteps)
1405
+
1406
+ # 6. Prepare latent variables
1407
+ if latents is None:
1408
+ latents = self.prepare_latents(
1409
+ image,
1410
+ latent_timestep,
1411
+ batch_size,
1412
+ num_images_per_prompt,
1413
+ prompt_embeds.dtype,
1414
+ device,
1415
+ generator,
1416
+ True,
1417
+ )
1418
+
1419
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1420
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1421
+
1422
+ # 7.1 Create tensor stating which controlnets to keep
1423
+ controlnet_keep = []
1424
+ for i in range(len(timesteps)):
1425
+ controlnet_keep.append(
1426
+ 1.0
1427
+ - float(i / len(timesteps) < control_guidance_start or (i + 1) / len(timesteps) > control_guidance_end)
1428
+ )
1429
+
1430
+ # 7.2 Prepare added time ids & embeddings
1431
+ original_size = original_size or (height, width)
1432
+ target_size = target_size or (height, width)
1433
+ for _image in control_image:
1434
+ if isinstance(_image, torch.Tensor):
1435
+ original_size = original_size or _image.shape[-2:]
1436
+
1437
+ if negative_original_size is None:
1438
+ negative_original_size = original_size
1439
+ if negative_target_size is None:
1440
+ negative_target_size = target_size
1441
+ add_text_embeds = pooled_prompt_embeds
1442
+
1443
+ if self.text_encoder_2 is None:
1444
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1445
+ else:
1446
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1447
+
1448
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1449
+ original_size,
1450
+ crops_coords_top_left,
1451
+ target_size,
1452
+ aesthetic_score,
1453
+ negative_aesthetic_score,
1454
+ negative_original_size,
1455
+ negative_crops_coords_top_left,
1456
+ negative_target_size,
1457
+ dtype=prompt_embeds.dtype,
1458
+ text_encoder_projection_dim=text_encoder_projection_dim,
1459
+ )
1460
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1461
+
1462
+ if self.do_classifier_free_guidance:
1463
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1464
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1465
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1466
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1467
+
1468
+ prompt_embeds = prompt_embeds.to(device)
1469
+ add_text_embeds = add_text_embeds.to(device)
1470
+ add_time_ids = add_time_ids.to(device)
1471
+ control_type = (
1472
+ control_type.reshape(1, -1)
1473
+ .to(device, dtype=prompt_embeds.dtype)
1474
+ .repeat(batch_size * num_images_per_prompt * 2, 1)
1475
+ )
1476
+
1477
+ # 8. Denoising loop
1478
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1479
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1480
+ for i, t in enumerate(timesteps):
1481
+ if self.interrupt:
1482
+ continue
1483
+
1484
+ # expand the latents if we are doing classifier free guidance
1485
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1486
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1487
+
1488
+ added_cond_kwargs = {
1489
+ "text_embeds": add_text_embeds,
1490
+ "time_ids": add_time_ids,
1491
+ }
1492
+
1493
+ # controlnet(s) inference
1494
+ if guess_mode and self.do_classifier_free_guidance:
1495
+ # Infer ControlNet only for the conditional batch.
1496
+ control_model_input = latents
1497
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1498
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1499
+ controlnet_added_cond_kwargs = {
1500
+ "text_embeds": add_text_embeds.chunk(2)[1],
1501
+ "time_ids": add_time_ids.chunk(2)[1],
1502
+ }
1503
+ else:
1504
+ control_model_input = latent_model_input
1505
+ controlnet_prompt_embeds = prompt_embeds
1506
+ controlnet_added_cond_kwargs = added_cond_kwargs
1507
+
1508
+ if isinstance(controlnet_keep[i], list):
1509
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1510
+ else:
1511
+ controlnet_cond_scale = controlnet_conditioning_scale
1512
+ if isinstance(controlnet_cond_scale, list):
1513
+ controlnet_cond_scale = controlnet_cond_scale[0]
1514
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1515
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1516
+ control_model_input,
1517
+ t,
1518
+ encoder_hidden_states=controlnet_prompt_embeds,
1519
+ controlnet_cond=control_image,
1520
+ control_type=control_type,
1521
+ control_type_idx=control_mode,
1522
+ conditioning_scale=cond_scale,
1523
+ guess_mode=guess_mode,
1524
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1525
+ return_dict=False,
1526
+ )
1527
+
1528
+ if guess_mode and self.do_classifier_free_guidance:
1529
+ # Inferred ControlNet only for the conditional batch.
1530
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1531
+ # add 0 to the unconditional batch to keep it unchanged.
1532
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1533
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1534
+
1535
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1536
+ added_cond_kwargs["image_embeds"] = image_embeds
1537
+
1538
+ # predict the noise residual
1539
+ noise_pred = self.unet(
1540
+ latent_model_input,
1541
+ t,
1542
+ encoder_hidden_states=prompt_embeds,
1543
+ cross_attention_kwargs=self.cross_attention_kwargs,
1544
+ down_block_additional_residuals=down_block_res_samples,
1545
+ mid_block_additional_residual=mid_block_res_sample,
1546
+ added_cond_kwargs=added_cond_kwargs,
1547
+ return_dict=False,
1548
+ )[0]
1549
+
1550
+ # perform guidance
1551
+ if self.do_classifier_free_guidance:
1552
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1553
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1554
+
1555
+ # compute the previous noisy sample x_t -> x_t-1
1556
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1557
+
1558
+ if callback_on_step_end is not None:
1559
+ callback_kwargs = {}
1560
+ for k in callback_on_step_end_tensor_inputs:
1561
+ callback_kwargs[k] = locals()[k]
1562
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1563
+
1564
+ latents = callback_outputs.pop("latents", latents)
1565
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1566
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1567
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1568
+
1569
+ # call the callback, if provided
1570
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1571
+ progress_bar.update()
1572
+ if callback is not None and i % callback_steps == 0:
1573
+ step_idx = i // getattr(self.scheduler, "order", 1)
1574
+ callback(step_idx, t, latents)
1575
+
1576
+ # If we do sequential model offloading, let's offload unet and controlnet
1577
+ # manually for max memory savings
1578
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1579
+ self.unet.to("cpu")
1580
+ self.controlnet.to("cpu")
1581
+ torch.cuda.empty_cache()
1582
+
1583
+ if not output_type == "latent":
1584
+ # make sure the VAE is in float32 mode, as it overflows in float16
1585
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1586
+
1587
+ if needs_upcasting:
1588
+ self.upcast_vae()
1589
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1590
+
1591
+ # unscale/denormalize the latents
1592
+ # denormalize with the mean and std if available and not None
1593
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1594
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1595
+ if has_latents_mean and has_latents_std:
1596
+ latents_mean = (
1597
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1598
+ )
1599
+ latents_std = (
1600
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1601
+ )
1602
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1603
+ else:
1604
+ latents = latents / self.vae.config.scaling_factor
1605
+
1606
+ image = self.vae.decode(latents, return_dict=False)[0]
1607
+
1608
+ # cast back to fp16 if needed
1609
+ if needs_upcasting:
1610
+ self.vae.to(dtype=torch.float16)
1611
+ else:
1612
+ image = latents
1613
+ return StableDiffusionXLPipelineOutput(images=image)
1614
+
1615
+ # apply watermark if available
1616
+ if self.watermark is not None:
1617
+ image = self.watermark.apply_watermark(image)
1618
+
1619
+ image = self.image_processor.postprocess(image, output_type=output_type)
1620
+
1621
+ # Offload all models
1622
+ self.maybe_free_model_hooks()
1623
+
1624
+ if not return_dict:
1625
+ return (image,)
1626
+
1627
+ return StableDiffusionXLPipelineOutput(images=image)