diffusers 0.29.2__py3-none-any.whl → 0.30.1__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 +2252 -0
  10. diffusers/loaders/peft.py +213 -5
  11. diffusers/loaders/single_file.py +3 -14
  12. diffusers/loaders/single_file_model.py +31 -10
  13. diffusers/loaders/single_file_utils.py +293 -8
  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 +1937 -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 +1271 -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 +403 -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 +543 -0
  41. diffusers/models/transformers/cogvideox_transformer_3d.py +485 -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 +746 -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 +50 -6
  208. diffusers/utils/hub_utils.py +45 -42
  209. diffusers/utils/import_utils.py +37 -15
  210. diffusers/utils/loading_utils.py +80 -3
  211. diffusers/utils/testing_utils.py +11 -8
  212. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/METADATA +73 -83
  213. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/RECORD +217 -164
  214. {diffusers-0.29.2.dist-info → diffusers-0.30.1.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.1.dist-info}/LICENSE +0 -0
  219. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/entry_points.txt +0 -0
  220. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1329 @@
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 CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
24
+
25
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
26
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
27
+ from ...loaders import FromSingleFileMixin, IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
28
+ from ...models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel
29
+ from ...models.lora import adjust_lora_scale_text_encoder
30
+ from ...schedulers import KarrasDiffusionSchedulers
31
+ from ...utils import (
32
+ USE_PEFT_BACKEND,
33
+ logging,
34
+ replace_example_docstring,
35
+ scale_lora_layers,
36
+ unscale_lora_layers,
37
+ )
38
+ from ...utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
39
+ from ..controlnet.multicontrolnet import MultiControlNetModel
40
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
41
+ from ..stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
42
+ from ..stable_diffusion.safety_checker import StableDiffusionSafetyChecker
43
+ from .pag_utils import PAGMixin
44
+
45
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+
49
+ EXAMPLE_DOC_STRING = """
50
+ Examples:
51
+ ```py
52
+ >>> # !pip install opencv-python transformers accelerate
53
+ >>> from diffusers import AutoPipelineForText2Image, ControlNetModel, UniPCMultistepScheduler
54
+ >>> from diffusers.utils import load_image
55
+ >>> import numpy as np
56
+ >>> import torch
57
+
58
+ >>> import cv2
59
+ >>> from PIL import Image
60
+
61
+ >>> # download an image
62
+ >>> image = load_image(
63
+ ... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
64
+ ... )
65
+ >>> image = np.array(image)
66
+
67
+ >>> # get canny image
68
+ >>> image = cv2.Canny(image, 100, 200)
69
+ >>> image = image[:, :, None]
70
+ >>> image = np.concatenate([image, image, image], axis=2)
71
+ >>> canny_image = Image.fromarray(image)
72
+
73
+ >>> # load control net and stable diffusion v1-5
74
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
75
+ >>> pipe = AutoPipelineForText2Image.from_pretrained(
76
+ ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16, enable_pag=True
77
+ ... )
78
+
79
+ >>> # speed up diffusion process with faster scheduler and memory optimization
80
+ >>> # remove following line if xformers is not installed
81
+ >>> pipe.enable_xformers_memory_efficient_attention()
82
+
83
+ >>> pipe.enable_model_cpu_offload()
84
+
85
+ >>> # generate image
86
+ >>> generator = torch.manual_seed(0)
87
+ >>> image = pipe(
88
+ ... "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting",
89
+ ... guidance_scale=7.5,
90
+ ... generator=generator,
91
+ ... image=canny_image,
92
+ ... pag_scale=10,
93
+ ... ).images[0]
94
+ ```
95
+ """
96
+
97
+
98
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
99
+ def retrieve_timesteps(
100
+ scheduler,
101
+ num_inference_steps: Optional[int] = None,
102
+ device: Optional[Union[str, torch.device]] = None,
103
+ timesteps: Optional[List[int]] = None,
104
+ sigmas: Optional[List[float]] = None,
105
+ **kwargs,
106
+ ):
107
+ """
108
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
109
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
110
+
111
+ Args:
112
+ scheduler (`SchedulerMixin`):
113
+ The scheduler to get timesteps from.
114
+ num_inference_steps (`int`):
115
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
116
+ must be `None`.
117
+ device (`str` or `torch.device`, *optional*):
118
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
119
+ timesteps (`List[int]`, *optional*):
120
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
121
+ `num_inference_steps` and `sigmas` must be `None`.
122
+ sigmas (`List[float]`, *optional*):
123
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
124
+ `num_inference_steps` and `timesteps` must be `None`.
125
+
126
+ Returns:
127
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
128
+ second element is the number of inference steps.
129
+ """
130
+ if timesteps is not None and sigmas is not None:
131
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
132
+ if timesteps is not None:
133
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
134
+ if not accepts_timesteps:
135
+ raise ValueError(
136
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
137
+ f" timestep schedules. Please check whether you are using the correct scheduler."
138
+ )
139
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
140
+ timesteps = scheduler.timesteps
141
+ num_inference_steps = len(timesteps)
142
+ elif sigmas is not None:
143
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
144
+ if not accept_sigmas:
145
+ raise ValueError(
146
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
147
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
148
+ )
149
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
150
+ timesteps = scheduler.timesteps
151
+ num_inference_steps = len(timesteps)
152
+ else:
153
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
154
+ timesteps = scheduler.timesteps
155
+ return timesteps, num_inference_steps
156
+
157
+
158
+ class StableDiffusionControlNetPAGPipeline(
159
+ DiffusionPipeline,
160
+ StableDiffusionMixin,
161
+ TextualInversionLoaderMixin,
162
+ StableDiffusionLoraLoaderMixin,
163
+ IPAdapterMixin,
164
+ FromSingleFileMixin,
165
+ PAGMixin,
166
+ ):
167
+ r"""
168
+ Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.
169
+
170
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
171
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
172
+
173
+ The pipeline also inherits the following loading methods:
174
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
175
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
176
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
177
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
178
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
179
+
180
+ Args:
181
+ vae ([`AutoencoderKL`]):
182
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
183
+ text_encoder ([`~transformers.CLIPTextModel`]):
184
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
185
+ tokenizer ([`~transformers.CLIPTokenizer`]):
186
+ A `CLIPTokenizer` to tokenize text.
187
+ unet ([`UNet2DConditionModel`]):
188
+ A `UNet2DConditionModel` to denoise the encoded image latents.
189
+ controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
190
+ Provides additional conditioning to the `unet` during the denoising process. If you set multiple
191
+ ControlNets as a list, the outputs from each ControlNet are added together to create one combined
192
+ additional conditioning.
193
+ scheduler ([`SchedulerMixin`]):
194
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
195
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
196
+ safety_checker ([`StableDiffusionSafetyChecker`]):
197
+ Classification module that estimates whether generated images could be considered offensive or harmful.
198
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
199
+ about a model's potential harms.
200
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
201
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
202
+ """
203
+
204
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
205
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
206
+ _exclude_from_cpu_offload = ["safety_checker"]
207
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
208
+
209
+ def __init__(
210
+ self,
211
+ vae: AutoencoderKL,
212
+ text_encoder: CLIPTextModel,
213
+ tokenizer: CLIPTokenizer,
214
+ unet: UNet2DConditionModel,
215
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
216
+ scheduler: KarrasDiffusionSchedulers,
217
+ safety_checker: StableDiffusionSafetyChecker,
218
+ feature_extractor: CLIPImageProcessor,
219
+ image_encoder: CLIPVisionModelWithProjection = None,
220
+ requires_safety_checker: bool = True,
221
+ pag_applied_layers: Union[str, List[str]] = "mid",
222
+ ):
223
+ super().__init__()
224
+
225
+ if safety_checker is None and requires_safety_checker:
226
+ logger.warning(
227
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
228
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
229
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
230
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
231
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
232
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
233
+ )
234
+
235
+ if safety_checker is not None and feature_extractor is None:
236
+ raise ValueError(
237
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
238
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
239
+ )
240
+
241
+ if isinstance(controlnet, (list, tuple)):
242
+ controlnet = MultiControlNetModel(controlnet)
243
+
244
+ self.register_modules(
245
+ vae=vae,
246
+ text_encoder=text_encoder,
247
+ tokenizer=tokenizer,
248
+ unet=unet,
249
+ controlnet=controlnet,
250
+ scheduler=scheduler,
251
+ safety_checker=safety_checker,
252
+ feature_extractor=feature_extractor,
253
+ image_encoder=image_encoder,
254
+ )
255
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
256
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
257
+ self.control_image_processor = VaeImageProcessor(
258
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
259
+ )
260
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
261
+
262
+ self.set_pag_applied_layers(pag_applied_layers)
263
+
264
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
265
+ def encode_prompt(
266
+ self,
267
+ prompt,
268
+ device,
269
+ num_images_per_prompt,
270
+ do_classifier_free_guidance,
271
+ negative_prompt=None,
272
+ prompt_embeds: Optional[torch.Tensor] = None,
273
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
274
+ lora_scale: Optional[float] = None,
275
+ clip_skip: Optional[int] = None,
276
+ ):
277
+ r"""
278
+ Encodes the prompt into text encoder hidden states.
279
+
280
+ Args:
281
+ prompt (`str` or `List[str]`, *optional*):
282
+ prompt to be encoded
283
+ device: (`torch.device`):
284
+ torch device
285
+ num_images_per_prompt (`int`):
286
+ number of images that should be generated per prompt
287
+ do_classifier_free_guidance (`bool`):
288
+ whether to use classifier free guidance or not
289
+ negative_prompt (`str` or `List[str]`, *optional*):
290
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
291
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
292
+ less than `1`).
293
+ prompt_embeds (`torch.Tensor`, *optional*):
294
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
295
+ provided, text embeddings will be generated from `prompt` input argument.
296
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
297
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
298
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
299
+ argument.
300
+ lora_scale (`float`, *optional*):
301
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
302
+ clip_skip (`int`, *optional*):
303
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
304
+ the output of the pre-final layer will be used for computing the prompt embeddings.
305
+ """
306
+ # set lora scale so that monkey patched LoRA
307
+ # function of text encoder can correctly access it
308
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
309
+ self._lora_scale = lora_scale
310
+
311
+ # dynamically adjust the LoRA scale
312
+ if not USE_PEFT_BACKEND:
313
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
314
+ else:
315
+ scale_lora_layers(self.text_encoder, lora_scale)
316
+
317
+ if prompt is not None and isinstance(prompt, str):
318
+ batch_size = 1
319
+ elif prompt is not None and isinstance(prompt, list):
320
+ batch_size = len(prompt)
321
+ else:
322
+ batch_size = prompt_embeds.shape[0]
323
+
324
+ if prompt_embeds is None:
325
+ # textual inversion: process multi-vector tokens if necessary
326
+ if isinstance(self, TextualInversionLoaderMixin):
327
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
328
+
329
+ text_inputs = self.tokenizer(
330
+ prompt,
331
+ padding="max_length",
332
+ max_length=self.tokenizer.model_max_length,
333
+ truncation=True,
334
+ return_tensors="pt",
335
+ )
336
+ text_input_ids = text_inputs.input_ids
337
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
338
+
339
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
340
+ text_input_ids, untruncated_ids
341
+ ):
342
+ removed_text = self.tokenizer.batch_decode(
343
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
344
+ )
345
+ logger.warning(
346
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
347
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
348
+ )
349
+
350
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
351
+ attention_mask = text_inputs.attention_mask.to(device)
352
+ else:
353
+ attention_mask = None
354
+
355
+ if clip_skip is None:
356
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
357
+ prompt_embeds = prompt_embeds[0]
358
+ else:
359
+ prompt_embeds = self.text_encoder(
360
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
361
+ )
362
+ # Access the `hidden_states` first, that contains a tuple of
363
+ # all the hidden states from the encoder layers. Then index into
364
+ # the tuple to access the hidden states from the desired layer.
365
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
366
+ # We also need to apply the final LayerNorm here to not mess with the
367
+ # representations. The `last_hidden_states` that we typically use for
368
+ # obtaining the final prompt representations passes through the LayerNorm
369
+ # layer.
370
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
371
+
372
+ if self.text_encoder is not None:
373
+ prompt_embeds_dtype = self.text_encoder.dtype
374
+ elif self.unet is not None:
375
+ prompt_embeds_dtype = self.unet.dtype
376
+ else:
377
+ prompt_embeds_dtype = prompt_embeds.dtype
378
+
379
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
380
+
381
+ bs_embed, seq_len, _ = prompt_embeds.shape
382
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
383
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
384
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
385
+
386
+ # get unconditional embeddings for classifier free guidance
387
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
388
+ uncond_tokens: List[str]
389
+ if negative_prompt is None:
390
+ uncond_tokens = [""] * batch_size
391
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
392
+ raise TypeError(
393
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
394
+ f" {type(prompt)}."
395
+ )
396
+ elif isinstance(negative_prompt, str):
397
+ uncond_tokens = [negative_prompt]
398
+ elif batch_size != len(negative_prompt):
399
+ raise ValueError(
400
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
401
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
402
+ " the batch size of `prompt`."
403
+ )
404
+ else:
405
+ uncond_tokens = negative_prompt
406
+
407
+ # textual inversion: process multi-vector tokens if necessary
408
+ if isinstance(self, TextualInversionLoaderMixin):
409
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
410
+
411
+ max_length = prompt_embeds.shape[1]
412
+ uncond_input = self.tokenizer(
413
+ uncond_tokens,
414
+ padding="max_length",
415
+ max_length=max_length,
416
+ truncation=True,
417
+ return_tensors="pt",
418
+ )
419
+
420
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
421
+ attention_mask = uncond_input.attention_mask.to(device)
422
+ else:
423
+ attention_mask = None
424
+
425
+ negative_prompt_embeds = self.text_encoder(
426
+ uncond_input.input_ids.to(device),
427
+ attention_mask=attention_mask,
428
+ )
429
+ negative_prompt_embeds = negative_prompt_embeds[0]
430
+
431
+ if do_classifier_free_guidance:
432
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
433
+ seq_len = negative_prompt_embeds.shape[1]
434
+
435
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
436
+
437
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
438
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
439
+
440
+ if self.text_encoder is not None:
441
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
442
+ # Retrieve the original scale by scaling back the LoRA layers
443
+ unscale_lora_layers(self.text_encoder, lora_scale)
444
+
445
+ return prompt_embeds, negative_prompt_embeds
446
+
447
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
448
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
449
+ dtype = next(self.image_encoder.parameters()).dtype
450
+
451
+ if not isinstance(image, torch.Tensor):
452
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
453
+
454
+ image = image.to(device=device, dtype=dtype)
455
+ if output_hidden_states:
456
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
457
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
458
+ uncond_image_enc_hidden_states = self.image_encoder(
459
+ torch.zeros_like(image), output_hidden_states=True
460
+ ).hidden_states[-2]
461
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
462
+ num_images_per_prompt, dim=0
463
+ )
464
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
465
+ else:
466
+ image_embeds = self.image_encoder(image).image_embeds
467
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
468
+ uncond_image_embeds = torch.zeros_like(image_embeds)
469
+
470
+ return image_embeds, uncond_image_embeds
471
+
472
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
473
+ def prepare_ip_adapter_image_embeds(
474
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
475
+ ):
476
+ image_embeds = []
477
+ if do_classifier_free_guidance:
478
+ negative_image_embeds = []
479
+ if ip_adapter_image_embeds is None:
480
+ if not isinstance(ip_adapter_image, list):
481
+ ip_adapter_image = [ip_adapter_image]
482
+
483
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
484
+ raise ValueError(
485
+ 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."
486
+ )
487
+
488
+ for single_ip_adapter_image, image_proj_layer in zip(
489
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
490
+ ):
491
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
492
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
493
+ single_ip_adapter_image, device, 1, output_hidden_state
494
+ )
495
+
496
+ image_embeds.append(single_image_embeds[None, :])
497
+ if do_classifier_free_guidance:
498
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
499
+ else:
500
+ for single_image_embeds in ip_adapter_image_embeds:
501
+ if do_classifier_free_guidance:
502
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
503
+ negative_image_embeds.append(single_negative_image_embeds)
504
+ image_embeds.append(single_image_embeds)
505
+
506
+ ip_adapter_image_embeds = []
507
+ for i, single_image_embeds in enumerate(image_embeds):
508
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
509
+ if do_classifier_free_guidance:
510
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
511
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
512
+
513
+ single_image_embeds = single_image_embeds.to(device=device)
514
+ ip_adapter_image_embeds.append(single_image_embeds)
515
+
516
+ return ip_adapter_image_embeds
517
+
518
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
519
+ def run_safety_checker(self, image, device, dtype):
520
+ if self.safety_checker is None:
521
+ has_nsfw_concept = None
522
+ else:
523
+ if torch.is_tensor(image):
524
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
525
+ else:
526
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
527
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
528
+ image, has_nsfw_concept = self.safety_checker(
529
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
530
+ )
531
+ return image, has_nsfw_concept
532
+
533
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
534
+ def prepare_extra_step_kwargs(self, generator, eta):
535
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
536
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
537
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
538
+ # and should be between [0, 1]
539
+
540
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
541
+ extra_step_kwargs = {}
542
+ if accepts_eta:
543
+ extra_step_kwargs["eta"] = eta
544
+
545
+ # check if the scheduler accepts generator
546
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
547
+ if accepts_generator:
548
+ extra_step_kwargs["generator"] = generator
549
+ return extra_step_kwargs
550
+
551
+ def check_inputs(
552
+ self,
553
+ prompt,
554
+ image,
555
+ negative_prompt=None,
556
+ prompt_embeds=None,
557
+ negative_prompt_embeds=None,
558
+ ip_adapter_image=None,
559
+ ip_adapter_image_embeds=None,
560
+ controlnet_conditioning_scale=1.0,
561
+ control_guidance_start=0.0,
562
+ control_guidance_end=1.0,
563
+ callback_on_step_end_tensor_inputs=None,
564
+ ):
565
+ if callback_on_step_end_tensor_inputs is not None and not all(
566
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
567
+ ):
568
+ raise ValueError(
569
+ 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]}"
570
+ )
571
+
572
+ if prompt is not None and prompt_embeds is not None:
573
+ raise ValueError(
574
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
575
+ " only forward one of the two."
576
+ )
577
+ elif prompt is None and prompt_embeds is None:
578
+ raise ValueError(
579
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
580
+ )
581
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
582
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
583
+
584
+ if negative_prompt is not None and negative_prompt_embeds is not None:
585
+ raise ValueError(
586
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
587
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
588
+ )
589
+
590
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
591
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
592
+ raise ValueError(
593
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
594
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
595
+ f" {negative_prompt_embeds.shape}."
596
+ )
597
+
598
+ # Check `image`
599
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
600
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
601
+ )
602
+ if (
603
+ isinstance(self.controlnet, ControlNetModel)
604
+ or is_compiled
605
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
606
+ ):
607
+ self.check_image(image, prompt, prompt_embeds)
608
+ elif (
609
+ isinstance(self.controlnet, MultiControlNetModel)
610
+ or is_compiled
611
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
612
+ ):
613
+ if not isinstance(image, list):
614
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
615
+
616
+ # When `image` is a nested list:
617
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
618
+ elif any(isinstance(i, list) for i in image):
619
+ transposed_image = [list(t) for t in zip(*image)]
620
+ if len(transposed_image) != len(self.controlnet.nets):
621
+ raise ValueError(
622
+ f"For multiple controlnets: if you pass`image` as a list of list, each sublist must have the same length as the number of controlnets, but the sublists in `image` got {len(transposed_image)} images and {len(self.controlnet.nets)} ControlNets."
623
+ )
624
+ for image_ in transposed_image:
625
+ self.check_image(image_, prompt, prompt_embeds)
626
+ elif len(image) != len(self.controlnet.nets):
627
+ raise ValueError(
628
+ 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."
629
+ )
630
+ else:
631
+ for image_ in image:
632
+ self.check_image(image_, prompt, prompt_embeds)
633
+ else:
634
+ assert False
635
+
636
+ # Check `controlnet_conditioning_scale`
637
+ if (
638
+ isinstance(self.controlnet, ControlNetModel)
639
+ or is_compiled
640
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
641
+ ):
642
+ if not isinstance(controlnet_conditioning_scale, float):
643
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
644
+ elif (
645
+ isinstance(self.controlnet, MultiControlNetModel)
646
+ or is_compiled
647
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
648
+ ):
649
+ if isinstance(controlnet_conditioning_scale, list):
650
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
651
+ raise ValueError(
652
+ "A single batch of varying conditioning scale settings (e.g. [[1.0, 0.5], [0.2, 0.8]]) is not supported at the moment. "
653
+ "The conditioning scale must be fixed across the batch."
654
+ )
655
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
656
+ self.controlnet.nets
657
+ ):
658
+ raise ValueError(
659
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
660
+ " the same length as the number of controlnets"
661
+ )
662
+ else:
663
+ assert False
664
+
665
+ if not isinstance(control_guidance_start, (tuple, list)):
666
+ control_guidance_start = [control_guidance_start]
667
+
668
+ if not isinstance(control_guidance_end, (tuple, list)):
669
+ control_guidance_end = [control_guidance_end]
670
+
671
+ if len(control_guidance_start) != len(control_guidance_end):
672
+ raise ValueError(
673
+ 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."
674
+ )
675
+
676
+ if isinstance(self.controlnet, MultiControlNetModel):
677
+ if len(control_guidance_start) != len(self.controlnet.nets):
678
+ raise ValueError(
679
+ 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)}."
680
+ )
681
+
682
+ for start, end in zip(control_guidance_start, control_guidance_end):
683
+ if start >= end:
684
+ raise ValueError(
685
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
686
+ )
687
+ if start < 0.0:
688
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
689
+ if end > 1.0:
690
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
691
+
692
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
693
+ raise ValueError(
694
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
695
+ )
696
+
697
+ if ip_adapter_image_embeds is not None:
698
+ if not isinstance(ip_adapter_image_embeds, list):
699
+ raise ValueError(
700
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
701
+ )
702
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
703
+ raise ValueError(
704
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
705
+ )
706
+
707
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
708
+ def check_image(self, image, prompt, prompt_embeds):
709
+ image_is_pil = isinstance(image, PIL.Image.Image)
710
+ image_is_tensor = isinstance(image, torch.Tensor)
711
+ image_is_np = isinstance(image, np.ndarray)
712
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
713
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
714
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
715
+
716
+ if (
717
+ not image_is_pil
718
+ and not image_is_tensor
719
+ and not image_is_np
720
+ and not image_is_pil_list
721
+ and not image_is_tensor_list
722
+ and not image_is_np_list
723
+ ):
724
+ raise TypeError(
725
+ 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)}"
726
+ )
727
+
728
+ if image_is_pil:
729
+ image_batch_size = 1
730
+ else:
731
+ image_batch_size = len(image)
732
+
733
+ if prompt is not None and isinstance(prompt, str):
734
+ prompt_batch_size = 1
735
+ elif prompt is not None and isinstance(prompt, list):
736
+ prompt_batch_size = len(prompt)
737
+ elif prompt_embeds is not None:
738
+ prompt_batch_size = prompt_embeds.shape[0]
739
+
740
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
741
+ raise ValueError(
742
+ 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}"
743
+ )
744
+
745
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
746
+ def prepare_image(
747
+ self,
748
+ image,
749
+ width,
750
+ height,
751
+ batch_size,
752
+ num_images_per_prompt,
753
+ device,
754
+ dtype,
755
+ do_classifier_free_guidance=False,
756
+ guess_mode=False,
757
+ ):
758
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
759
+ image_batch_size = image.shape[0]
760
+
761
+ if image_batch_size == 1:
762
+ repeat_by = batch_size
763
+ else:
764
+ # image batch size is the same as prompt batch size
765
+ repeat_by = num_images_per_prompt
766
+
767
+ image = image.repeat_interleave(repeat_by, dim=0)
768
+
769
+ image = image.to(device=device, dtype=dtype)
770
+
771
+ if do_classifier_free_guidance and not guess_mode:
772
+ image = torch.cat([image] * 2)
773
+
774
+ return image
775
+
776
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
777
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
778
+ shape = (
779
+ batch_size,
780
+ num_channels_latents,
781
+ int(height) // self.vae_scale_factor,
782
+ int(width) // self.vae_scale_factor,
783
+ )
784
+ if isinstance(generator, list) and len(generator) != batch_size:
785
+ raise ValueError(
786
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
787
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
788
+ )
789
+
790
+ if latents is None:
791
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
792
+ else:
793
+ latents = latents.to(device)
794
+
795
+ # scale the initial noise by the standard deviation required by the scheduler
796
+ latents = latents * self.scheduler.init_noise_sigma
797
+ return latents
798
+
799
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
800
+ def get_guidance_scale_embedding(
801
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
802
+ ) -> torch.Tensor:
803
+ """
804
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
805
+
806
+ Args:
807
+ w (`torch.Tensor`):
808
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
809
+ embedding_dim (`int`, *optional*, defaults to 512):
810
+ Dimension of the embeddings to generate.
811
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
812
+ Data type of the generated embeddings.
813
+
814
+ Returns:
815
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
816
+ """
817
+ assert len(w.shape) == 1
818
+ w = w * 1000.0
819
+
820
+ half_dim = embedding_dim // 2
821
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
822
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
823
+ emb = w.to(dtype)[:, None] * emb[None, :]
824
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
825
+ if embedding_dim % 2 == 1: # zero pad
826
+ emb = torch.nn.functional.pad(emb, (0, 1))
827
+ assert emb.shape == (w.shape[0], embedding_dim)
828
+ return emb
829
+
830
+ @property
831
+ def guidance_scale(self):
832
+ return self._guidance_scale
833
+
834
+ @property
835
+ def clip_skip(self):
836
+ return self._clip_skip
837
+
838
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
839
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
840
+ # corresponds to doing no classifier free guidance.
841
+ @property
842
+ def do_classifier_free_guidance(self):
843
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
844
+
845
+ @property
846
+ def cross_attention_kwargs(self):
847
+ return self._cross_attention_kwargs
848
+
849
+ @property
850
+ def num_timesteps(self):
851
+ return self._num_timesteps
852
+
853
+ @torch.no_grad()
854
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
855
+ def __call__(
856
+ self,
857
+ prompt: Union[str, List[str]] = None,
858
+ image: PipelineImageInput = None,
859
+ height: Optional[int] = None,
860
+ width: Optional[int] = None,
861
+ num_inference_steps: int = 50,
862
+ timesteps: List[int] = None,
863
+ sigmas: List[float] = None,
864
+ guidance_scale: float = 7.5,
865
+ negative_prompt: Optional[Union[str, List[str]]] = None,
866
+ num_images_per_prompt: Optional[int] = 1,
867
+ eta: float = 0.0,
868
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
869
+ latents: Optional[torch.Tensor] = None,
870
+ prompt_embeds: Optional[torch.Tensor] = None,
871
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
872
+ ip_adapter_image: Optional[PipelineImageInput] = None,
873
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
874
+ output_type: Optional[str] = "pil",
875
+ return_dict: bool = True,
876
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
877
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
878
+ guess_mode: bool = False,
879
+ control_guidance_start: Union[float, List[float]] = 0.0,
880
+ control_guidance_end: Union[float, List[float]] = 1.0,
881
+ clip_skip: Optional[int] = None,
882
+ callback_on_step_end: Optional[
883
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
884
+ ] = None,
885
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
886
+ pag_scale: float = 3.0,
887
+ pag_adaptive_scale: float = 0.0,
888
+ ):
889
+ r"""
890
+ The call function to the pipeline for generation.
891
+
892
+ Args:
893
+ prompt (`str` or `List[str]`, *optional*):
894
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
895
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
896
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
897
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
898
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
899
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
900
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
901
+ images must be passed as a list such that each element of the list can be correctly batched for input
902
+ to a single ControlNet. When `prompt` is a list, and if a list of images is passed for a single
903
+ ControlNet, each will be paired with each prompt in the `prompt` list. This also applies to multiple
904
+ ControlNets, where a list of image lists can be passed to batch for each prompt and each ControlNet.
905
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
906
+ The height in pixels of the generated image.
907
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
908
+ The width in pixels of the generated image.
909
+ num_inference_steps (`int`, *optional*, defaults to 50):
910
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
911
+ expense of slower inference.
912
+ timesteps (`List[int]`, *optional*):
913
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
914
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
915
+ passed will be used. Must be in descending order.
916
+ sigmas (`List[float]`, *optional*):
917
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
918
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
919
+ will be used.
920
+ guidance_scale (`float`, *optional*, defaults to 7.5):
921
+ A higher guidance scale value encourages the model to generate images closely linked to the text
922
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
923
+ negative_prompt (`str` or `List[str]`, *optional*):
924
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
925
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
926
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
927
+ The number of images to generate per prompt.
928
+ eta (`float`, *optional*, defaults to 0.0):
929
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
930
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
931
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
932
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
933
+ generation deterministic.
934
+ latents (`torch.Tensor`, *optional*):
935
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
936
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
937
+ tensor is generated by sampling using the supplied random `generator`.
938
+ prompt_embeds (`torch.Tensor`, *optional*):
939
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
940
+ provided, text embeddings are generated from the `prompt` input argument.
941
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
942
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
943
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
944
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
945
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
946
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
947
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
948
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
949
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
950
+ output_type (`str`, *optional*, defaults to `"pil"`):
951
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
952
+ return_dict (`bool`, *optional*, defaults to `True`):
953
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
954
+ plain tuple.
955
+ cross_attention_kwargs (`dict`, *optional*):
956
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
957
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
958
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
959
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
960
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
961
+ the corresponding scale as a list.
962
+ guess_mode (`bool`, *optional*, defaults to `False`):
963
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
964
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
965
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
966
+ The percentage of total steps at which the ControlNet starts applying.
967
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
968
+ The percentage of total steps at which the ControlNet stops applying.
969
+ clip_skip (`int`, *optional*):
970
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
971
+ the output of the pre-final layer will be used for computing the prompt embeddings.
972
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
973
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
974
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
975
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
976
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
977
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
978
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
979
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
980
+ `._callback_tensor_inputs` attribute of your pipeline class.
981
+ pag_scale (`float`, *optional*, defaults to 3.0):
982
+ The scale factor for the perturbed attention guidance. If it is set to 0.0, the perturbed attention
983
+ guidance will not be used.
984
+ pag_adaptive_scale (`float`, *optional*, defaults to 0.0):
985
+ The adaptive scale factor for the perturbed attention guidance. If it is set to 0.0, `pag_scale` is
986
+ used.
987
+
988
+ Examples:
989
+
990
+ Returns:
991
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
992
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
993
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
994
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
995
+ "not-safe-for-work" (nsfw) content.
996
+ """
997
+
998
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
999
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1000
+
1001
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1002
+
1003
+ # align format for control guidance
1004
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1005
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1006
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1007
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1008
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1009
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1010
+ control_guidance_start, control_guidance_end = (
1011
+ mult * [control_guidance_start],
1012
+ mult * [control_guidance_end],
1013
+ )
1014
+
1015
+ # 1. Check inputs. Raise error if not correct
1016
+ self.check_inputs(
1017
+ prompt,
1018
+ image,
1019
+ negative_prompt,
1020
+ prompt_embeds,
1021
+ negative_prompt_embeds,
1022
+ ip_adapter_image,
1023
+ ip_adapter_image_embeds,
1024
+ controlnet_conditioning_scale,
1025
+ control_guidance_start,
1026
+ control_guidance_end,
1027
+ callback_on_step_end_tensor_inputs,
1028
+ )
1029
+
1030
+ self._guidance_scale = guidance_scale
1031
+ self._clip_skip = clip_skip
1032
+ self._cross_attention_kwargs = cross_attention_kwargs
1033
+ self._pag_scale = pag_scale
1034
+ self._pag_adaptive_scale = pag_adaptive_scale
1035
+
1036
+ # 2. Define call parameters
1037
+ if prompt is not None and isinstance(prompt, str):
1038
+ batch_size = 1
1039
+ elif prompt is not None and isinstance(prompt, list):
1040
+ batch_size = len(prompt)
1041
+ else:
1042
+ batch_size = prompt_embeds.shape[0]
1043
+
1044
+ device = self._execution_device
1045
+
1046
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1047
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1048
+
1049
+ global_pool_conditions = (
1050
+ controlnet.config.global_pool_conditions
1051
+ if isinstance(controlnet, ControlNetModel)
1052
+ else controlnet.nets[0].config.global_pool_conditions
1053
+ )
1054
+ guess_mode = guess_mode or global_pool_conditions
1055
+
1056
+ # 3. Encode input prompt
1057
+ text_encoder_lora_scale = (
1058
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1059
+ )
1060
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1061
+ prompt,
1062
+ device,
1063
+ num_images_per_prompt,
1064
+ self.do_classifier_free_guidance,
1065
+ negative_prompt,
1066
+ prompt_embeds=prompt_embeds,
1067
+ negative_prompt_embeds=negative_prompt_embeds,
1068
+ lora_scale=text_encoder_lora_scale,
1069
+ clip_skip=self.clip_skip,
1070
+ )
1071
+ # For classifier free guidance, we need to do two forward passes.
1072
+ # Here we concatenate the unconditional and text embeddings into a single batch
1073
+ # to avoid doing two forward passes
1074
+ if self.do_perturbed_attention_guidance:
1075
+ prompt_embeds = self._prepare_perturbed_attention_guidance(
1076
+ prompt_embeds, negative_prompt_embeds, self.do_classifier_free_guidance
1077
+ )
1078
+ elif self.do_classifier_free_guidance:
1079
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1080
+
1081
+ # 4. Prepare image
1082
+ if isinstance(controlnet, ControlNetModel):
1083
+ image = self.prepare_image(
1084
+ image=image,
1085
+ width=width,
1086
+ height=height,
1087
+ batch_size=batch_size * num_images_per_prompt,
1088
+ num_images_per_prompt=num_images_per_prompt,
1089
+ device=device,
1090
+ dtype=controlnet.dtype,
1091
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1092
+ guess_mode=guess_mode,
1093
+ )
1094
+ height, width = image.shape[-2:]
1095
+ elif isinstance(controlnet, MultiControlNetModel):
1096
+ images = []
1097
+
1098
+ # Nested lists as ControlNet condition
1099
+ if isinstance(image[0], list):
1100
+ # Transpose the nested image list
1101
+ image = [list(t) for t in zip(*image)]
1102
+
1103
+ for image_ in image:
1104
+ image_ = self.prepare_image(
1105
+ image=image_,
1106
+ width=width,
1107
+ height=height,
1108
+ batch_size=batch_size * num_images_per_prompt,
1109
+ num_images_per_prompt=num_images_per_prompt,
1110
+ device=device,
1111
+ dtype=controlnet.dtype,
1112
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1113
+ guess_mode=guess_mode,
1114
+ )
1115
+
1116
+ images.append(image_)
1117
+
1118
+ image = images
1119
+ height, width = image[0].shape[-2:]
1120
+ else:
1121
+ assert False
1122
+
1123
+ # 5. Prepare timesteps
1124
+ timesteps, num_inference_steps = retrieve_timesteps(
1125
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1126
+ )
1127
+ self._num_timesteps = len(timesteps)
1128
+
1129
+ # 6. Prepare latent variables
1130
+ num_channels_latents = self.unet.config.in_channels
1131
+ latents = self.prepare_latents(
1132
+ batch_size * num_images_per_prompt,
1133
+ num_channels_latents,
1134
+ height,
1135
+ width,
1136
+ prompt_embeds.dtype,
1137
+ device,
1138
+ generator,
1139
+ latents,
1140
+ )
1141
+
1142
+ # 6.5 Optionally get Guidance Scale Embedding
1143
+ timestep_cond = None
1144
+ if self.unet.config.time_cond_proj_dim is not None:
1145
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1146
+ timestep_cond = self.get_guidance_scale_embedding(
1147
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1148
+ ).to(device=device, dtype=latents.dtype)
1149
+
1150
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1151
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1152
+
1153
+ # 7.1 Add image embeds for IP-Adapter
1154
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1155
+ ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
1156
+ ip_adapter_image,
1157
+ ip_adapter_image_embeds,
1158
+ device,
1159
+ batch_size * num_images_per_prompt,
1160
+ self.do_classifier_free_guidance,
1161
+ )
1162
+ for i, image_embeds in enumerate(ip_adapter_image_embeds):
1163
+ negative_image_embeds = None
1164
+ if self.do_classifier_free_guidance:
1165
+ negative_image_embeds, image_embeds = image_embeds.chunk(2)
1166
+
1167
+ if self.do_perturbed_attention_guidance:
1168
+ image_embeds = self._prepare_perturbed_attention_guidance(
1169
+ image_embeds, negative_image_embeds, self.do_classifier_free_guidance
1170
+ )
1171
+ elif self.do_classifier_free_guidance:
1172
+ image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0)
1173
+ image_embeds = image_embeds.to(device)
1174
+ ip_adapter_image_embeds[i] = image_embeds
1175
+
1176
+ added_cond_kwargs = (
1177
+ {"image_embeds": ip_adapter_image_embeds}
1178
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
1179
+ else None
1180
+ )
1181
+
1182
+ controlnet_prompt_embeds = prompt_embeds
1183
+
1184
+ # 7.2 Create tensor stating which controlnets to keep
1185
+ controlnet_keep = []
1186
+ for i in range(len(timesteps)):
1187
+ keeps = [
1188
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1189
+ for s, e in zip(control_guidance_start, control_guidance_end)
1190
+ ]
1191
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1192
+
1193
+ images = image if isinstance(image, list) else [image]
1194
+ for i, single_image in enumerate(images):
1195
+ if self.do_classifier_free_guidance:
1196
+ single_image = single_image.chunk(2)[0]
1197
+
1198
+ if self.do_perturbed_attention_guidance:
1199
+ single_image = self._prepare_perturbed_attention_guidance(
1200
+ single_image, single_image, self.do_classifier_free_guidance
1201
+ )
1202
+ elif self.do_classifier_free_guidance:
1203
+ single_image = torch.cat([single_image] * 2)
1204
+ single_image = single_image.to(device)
1205
+ images[i] = single_image
1206
+
1207
+ image = images if isinstance(image, list) else images[0]
1208
+
1209
+ # 8. Denoising loop
1210
+ if self.do_perturbed_attention_guidance:
1211
+ original_attn_proc = self.unet.attn_processors
1212
+ self._set_pag_attn_processor(
1213
+ pag_applied_layers=self.pag_applied_layers,
1214
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1215
+ )
1216
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1217
+ is_unet_compiled = is_compiled_module(self.unet)
1218
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
1219
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1220
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1221
+ for i, t in enumerate(timesteps):
1222
+ # Relevant thread:
1223
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1224
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1225
+ torch._inductor.cudagraph_mark_step_begin()
1226
+ # expand the latents if we are doing classifier free guidance
1227
+ latent_model_input = torch.cat([latents] * (prompt_embeds.shape[0] // latents.shape[0]))
1228
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1229
+
1230
+ # controlnet(s) inference
1231
+ control_model_input = latent_model_input
1232
+
1233
+ if isinstance(controlnet_keep[i], list):
1234
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1235
+ else:
1236
+ controlnet_cond_scale = controlnet_conditioning_scale
1237
+ if isinstance(controlnet_cond_scale, list):
1238
+ controlnet_cond_scale = controlnet_cond_scale[0]
1239
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1240
+
1241
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1242
+ control_model_input,
1243
+ t,
1244
+ encoder_hidden_states=controlnet_prompt_embeds,
1245
+ controlnet_cond=image,
1246
+ conditioning_scale=cond_scale,
1247
+ guess_mode=guess_mode,
1248
+ return_dict=False,
1249
+ )
1250
+
1251
+ if guess_mode and self.do_classifier_free_guidance:
1252
+ # Inferred ControlNet only for the conditional batch.
1253
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1254
+ # add 0 to the unconditional batch to keep it unchanged.
1255
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1256
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1257
+
1258
+ # predict the noise residual
1259
+ noise_pred = self.unet(
1260
+ latent_model_input,
1261
+ t,
1262
+ encoder_hidden_states=prompt_embeds,
1263
+ timestep_cond=timestep_cond,
1264
+ cross_attention_kwargs=self.cross_attention_kwargs,
1265
+ down_block_additional_residuals=down_block_res_samples,
1266
+ mid_block_additional_residual=mid_block_res_sample,
1267
+ added_cond_kwargs=added_cond_kwargs,
1268
+ return_dict=False,
1269
+ )[0]
1270
+
1271
+ # perform guidance
1272
+ if self.do_perturbed_attention_guidance:
1273
+ noise_pred = self._apply_perturbed_attention_guidance(
1274
+ noise_pred, self.do_classifier_free_guidance, self.guidance_scale, t
1275
+ )
1276
+ elif self.do_classifier_free_guidance:
1277
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1278
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1279
+
1280
+ # compute the previous noisy sample x_t -> x_t-1
1281
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1282
+
1283
+ if callback_on_step_end is not None:
1284
+ callback_kwargs = {}
1285
+ for k in callback_on_step_end_tensor_inputs:
1286
+ callback_kwargs[k] = locals()[k]
1287
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1288
+
1289
+ latents = callback_outputs.pop("latents", latents)
1290
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1291
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1292
+
1293
+ # call the callback, if provided
1294
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1295
+ progress_bar.update()
1296
+
1297
+ # If we do sequential model offloading, let's offload unet and controlnet
1298
+ # manually for max memory savings
1299
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1300
+ self.unet.to("cpu")
1301
+ self.controlnet.to("cpu")
1302
+ torch.cuda.empty_cache()
1303
+
1304
+ if not output_type == "latent":
1305
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1306
+ 0
1307
+ ]
1308
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1309
+ else:
1310
+ image = latents
1311
+ has_nsfw_concept = None
1312
+
1313
+ if has_nsfw_concept is None:
1314
+ do_denormalize = [True] * image.shape[0]
1315
+ else:
1316
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1317
+
1318
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1319
+
1320
+ # Offload all models
1321
+ self.maybe_free_model_hooks()
1322
+
1323
+ if self.do_perturbed_attention_guidance:
1324
+ self.unet.set_attn_processor(original_attn_proc)
1325
+
1326
+ if not return_dict:
1327
+ return (image, has_nsfw_concept)
1328
+
1329
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)