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