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