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,1333 @@
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
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from transformers import (
20
+ CLIPImageProcessor,
21
+ CLIPTextModel,
22
+ CLIPTextModelWithProjection,
23
+ CLIPTokenizer,
24
+ CLIPVisionModelWithProjection,
25
+ )
26
+
27
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
28
+ from ...loaders import (
29
+ FromSingleFileMixin,
30
+ IPAdapterMixin,
31
+ StableDiffusionXLLoraLoaderMixin,
32
+ TextualInversionLoaderMixin,
33
+ )
34
+ from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
35
+ from ...models.attention_processor import (
36
+ AttnProcessor2_0,
37
+ FusedAttnProcessor2_0,
38
+ XFormersAttnProcessor,
39
+ )
40
+ from ...models.lora import adjust_lora_scale_text_encoder
41
+ from ...schedulers import KarrasDiffusionSchedulers
42
+ from ...utils import (
43
+ USE_PEFT_BACKEND,
44
+ is_invisible_watermark_available,
45
+ is_torch_xla_available,
46
+ logging,
47
+ replace_example_docstring,
48
+ scale_lora_layers,
49
+ unscale_lora_layers,
50
+ )
51
+ from ...utils.torch_utils import randn_tensor
52
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
53
+ from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
54
+ from .pag_utils import PAGMixin
55
+
56
+
57
+ if is_invisible_watermark_available():
58
+ from ..stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
59
+
60
+ if is_torch_xla_available():
61
+ import torch_xla.core.xla_model as xm
62
+
63
+ XLA_AVAILABLE = True
64
+ else:
65
+ XLA_AVAILABLE = False
66
+
67
+
68
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
69
+
70
+ EXAMPLE_DOC_STRING = """
71
+ Examples:
72
+ ```py
73
+ >>> import torch
74
+ >>> from diffusers import AutoPipelineForText2Image
75
+
76
+ >>> pipe = AutoPipelineForText2Image.from_pretrained(
77
+ ... "stabilityai/stable-diffusion-xl-base-1.0",
78
+ ... torch_dtype=torch.float16,
79
+ ... enable_pag=True,
80
+ ... )
81
+ >>> pipe = pipe.to("cuda")
82
+
83
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
84
+ >>> image = pipe(prompt, pag_scale=0.3).images[0]
85
+ ```
86
+ """
87
+
88
+
89
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
90
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
91
+ """
92
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
93
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
94
+ """
95
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
96
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
97
+ # rescale the results from guidance (fixes overexposure)
98
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
99
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
100
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
101
+ return noise_cfg
102
+
103
+
104
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
105
+ def retrieve_timesteps(
106
+ scheduler,
107
+ num_inference_steps: Optional[int] = None,
108
+ device: Optional[Union[str, torch.device]] = None,
109
+ timesteps: Optional[List[int]] = None,
110
+ sigmas: Optional[List[float]] = None,
111
+ **kwargs,
112
+ ):
113
+ """
114
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
115
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
116
+
117
+ Args:
118
+ scheduler (`SchedulerMixin`):
119
+ The scheduler to get timesteps from.
120
+ num_inference_steps (`int`):
121
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
122
+ must be `None`.
123
+ device (`str` or `torch.device`, *optional*):
124
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
125
+ timesteps (`List[int]`, *optional*):
126
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
127
+ `num_inference_steps` and `sigmas` must be `None`.
128
+ sigmas (`List[float]`, *optional*):
129
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
130
+ `num_inference_steps` and `timesteps` must be `None`.
131
+
132
+ Returns:
133
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
134
+ second element is the number of inference steps.
135
+ """
136
+ if timesteps is not None and sigmas is not None:
137
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
138
+ if timesteps is not None:
139
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
140
+ if not accepts_timesteps:
141
+ raise ValueError(
142
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
143
+ f" timestep schedules. Please check whether you are using the correct scheduler."
144
+ )
145
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
146
+ timesteps = scheduler.timesteps
147
+ num_inference_steps = len(timesteps)
148
+ elif sigmas is not None:
149
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
150
+ if not accept_sigmas:
151
+ raise ValueError(
152
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
153
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
154
+ )
155
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
156
+ timesteps = scheduler.timesteps
157
+ num_inference_steps = len(timesteps)
158
+ else:
159
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
160
+ timesteps = scheduler.timesteps
161
+ return timesteps, num_inference_steps
162
+
163
+
164
+ class StableDiffusionXLPAGPipeline(
165
+ DiffusionPipeline,
166
+ StableDiffusionMixin,
167
+ FromSingleFileMixin,
168
+ StableDiffusionXLLoraLoaderMixin,
169
+ TextualInversionLoaderMixin,
170
+ IPAdapterMixin,
171
+ PAGMixin,
172
+ ):
173
+ r"""
174
+ Pipeline for text-to-image generation using Stable Diffusion XL.
175
+
176
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
177
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
178
+
179
+ The pipeline also inherits the following loading methods:
180
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
181
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
182
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
183
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
184
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
185
+
186
+ Args:
187
+ vae ([`AutoencoderKL`]):
188
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
189
+ text_encoder ([`CLIPTextModel`]):
190
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
191
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
192
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
193
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
194
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
195
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
196
+ specifically the
197
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
198
+ variant.
199
+ tokenizer (`CLIPTokenizer`):
200
+ Tokenizer of class
201
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
202
+ tokenizer_2 (`CLIPTokenizer`):
203
+ Second Tokenizer of class
204
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
205
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
206
+ scheduler ([`SchedulerMixin`]):
207
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
208
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
209
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
210
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
211
+ `stabilityai/stable-diffusion-xl-base-1-0`.
212
+ add_watermarker (`bool`, *optional*):
213
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
214
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
215
+ watermarker will be used.
216
+ """
217
+
218
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
219
+ _optional_components = [
220
+ "tokenizer",
221
+ "tokenizer_2",
222
+ "text_encoder",
223
+ "text_encoder_2",
224
+ "image_encoder",
225
+ "feature_extractor",
226
+ ]
227
+ _callback_tensor_inputs = [
228
+ "latents",
229
+ "prompt_embeds",
230
+ "negative_prompt_embeds",
231
+ "add_text_embeds",
232
+ "add_time_ids",
233
+ "negative_pooled_prompt_embeds",
234
+ "negative_add_time_ids",
235
+ ]
236
+
237
+ def __init__(
238
+ self,
239
+ vae: AutoencoderKL,
240
+ text_encoder: CLIPTextModel,
241
+ text_encoder_2: CLIPTextModelWithProjection,
242
+ tokenizer: CLIPTokenizer,
243
+ tokenizer_2: CLIPTokenizer,
244
+ unet: UNet2DConditionModel,
245
+ scheduler: KarrasDiffusionSchedulers,
246
+ image_encoder: CLIPVisionModelWithProjection = None,
247
+ feature_extractor: CLIPImageProcessor = None,
248
+ force_zeros_for_empty_prompt: bool = True,
249
+ add_watermarker: Optional[bool] = None,
250
+ pag_applied_layers: Union[str, List[str]] = "mid", # ["mid"],["down.block_1"],["up.block_0.attentions_0"]
251
+ ):
252
+ super().__init__()
253
+
254
+ self.register_modules(
255
+ vae=vae,
256
+ text_encoder=text_encoder,
257
+ text_encoder_2=text_encoder_2,
258
+ tokenizer=tokenizer,
259
+ tokenizer_2=tokenizer_2,
260
+ unet=unet,
261
+ scheduler=scheduler,
262
+ image_encoder=image_encoder,
263
+ feature_extractor=feature_extractor,
264
+ )
265
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
266
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
267
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
268
+
269
+ self.default_sample_size = self.unet.config.sample_size
270
+
271
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
272
+
273
+ if add_watermarker:
274
+ self.watermark = StableDiffusionXLWatermarker()
275
+ else:
276
+ self.watermark = None
277
+
278
+ self.set_pag_applied_layers(pag_applied_layers)
279
+
280
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
281
+ def encode_prompt(
282
+ self,
283
+ prompt: str,
284
+ prompt_2: Optional[str] = None,
285
+ device: Optional[torch.device] = None,
286
+ num_images_per_prompt: int = 1,
287
+ do_classifier_free_guidance: bool = True,
288
+ negative_prompt: Optional[str] = None,
289
+ negative_prompt_2: Optional[str] = None,
290
+ prompt_embeds: Optional[torch.Tensor] = None,
291
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
292
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
293
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
294
+ lora_scale: Optional[float] = None,
295
+ clip_skip: Optional[int] = None,
296
+ ):
297
+ r"""
298
+ Encodes the prompt into text encoder hidden states.
299
+
300
+ Args:
301
+ prompt (`str` or `List[str]`, *optional*):
302
+ prompt to be encoded
303
+ prompt_2 (`str` or `List[str]`, *optional*):
304
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
305
+ used in both text-encoders
306
+ device: (`torch.device`):
307
+ torch device
308
+ num_images_per_prompt (`int`):
309
+ number of images that should be generated per prompt
310
+ do_classifier_free_guidance (`bool`):
311
+ whether to use classifier free guidance or not
312
+ negative_prompt (`str` or `List[str]`, *optional*):
313
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
314
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
315
+ less than `1`).
316
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
317
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
318
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
319
+ prompt_embeds (`torch.Tensor`, *optional*):
320
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
321
+ provided, text embeddings will be generated from `prompt` input argument.
322
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
323
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
324
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
325
+ argument.
326
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
327
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
328
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
329
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
330
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
331
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
332
+ input argument.
333
+ lora_scale (`float`, *optional*):
334
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
335
+ clip_skip (`int`, *optional*):
336
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
337
+ the output of the pre-final layer will be used for computing the prompt embeddings.
338
+ """
339
+ device = device or self._execution_device
340
+
341
+ # set lora scale so that monkey patched LoRA
342
+ # function of text encoder can correctly access it
343
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
344
+ self._lora_scale = lora_scale
345
+
346
+ # dynamically adjust the LoRA scale
347
+ if self.text_encoder is not None:
348
+ if not USE_PEFT_BACKEND:
349
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
350
+ else:
351
+ scale_lora_layers(self.text_encoder, lora_scale)
352
+
353
+ if self.text_encoder_2 is not None:
354
+ if not USE_PEFT_BACKEND:
355
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
356
+ else:
357
+ scale_lora_layers(self.text_encoder_2, lora_scale)
358
+
359
+ prompt = [prompt] if isinstance(prompt, str) else prompt
360
+
361
+ if prompt is not None:
362
+ batch_size = len(prompt)
363
+ else:
364
+ batch_size = prompt_embeds.shape[0]
365
+
366
+ # Define tokenizers and text encoders
367
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
368
+ text_encoders = (
369
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
370
+ )
371
+
372
+ if prompt_embeds is None:
373
+ prompt_2 = prompt_2 or prompt
374
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
375
+
376
+ # textual inversion: process multi-vector tokens if necessary
377
+ prompt_embeds_list = []
378
+ prompts = [prompt, prompt_2]
379
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
380
+ if isinstance(self, TextualInversionLoaderMixin):
381
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
382
+
383
+ text_inputs = tokenizer(
384
+ prompt,
385
+ padding="max_length",
386
+ max_length=tokenizer.model_max_length,
387
+ truncation=True,
388
+ return_tensors="pt",
389
+ )
390
+
391
+ text_input_ids = text_inputs.input_ids
392
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
393
+
394
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
395
+ text_input_ids, untruncated_ids
396
+ ):
397
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
398
+ logger.warning(
399
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
400
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
401
+ )
402
+
403
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
404
+
405
+ # We are only ALWAYS interested in the pooled output of the final text encoder
406
+ pooled_prompt_embeds = prompt_embeds[0]
407
+ if clip_skip is None:
408
+ prompt_embeds = prompt_embeds.hidden_states[-2]
409
+ else:
410
+ # "2" because SDXL always indexes from the penultimate layer.
411
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
412
+
413
+ prompt_embeds_list.append(prompt_embeds)
414
+
415
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
416
+
417
+ # get unconditional embeddings for classifier free guidance
418
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
419
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
420
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
421
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
422
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
423
+ negative_prompt = negative_prompt or ""
424
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
425
+
426
+ # normalize str to list
427
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
428
+ negative_prompt_2 = (
429
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
430
+ )
431
+
432
+ uncond_tokens: List[str]
433
+ if prompt is not None and type(prompt) is not type(negative_prompt):
434
+ raise TypeError(
435
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
436
+ f" {type(prompt)}."
437
+ )
438
+ elif batch_size != len(negative_prompt):
439
+ raise ValueError(
440
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
441
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
442
+ " the batch size of `prompt`."
443
+ )
444
+ else:
445
+ uncond_tokens = [negative_prompt, negative_prompt_2]
446
+
447
+ negative_prompt_embeds_list = []
448
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
449
+ if isinstance(self, TextualInversionLoaderMixin):
450
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
451
+
452
+ max_length = prompt_embeds.shape[1]
453
+ uncond_input = tokenizer(
454
+ negative_prompt,
455
+ padding="max_length",
456
+ max_length=max_length,
457
+ truncation=True,
458
+ return_tensors="pt",
459
+ )
460
+
461
+ negative_prompt_embeds = text_encoder(
462
+ uncond_input.input_ids.to(device),
463
+ output_hidden_states=True,
464
+ )
465
+ # We are only ALWAYS interested in the pooled output of the final text encoder
466
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
467
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
468
+
469
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
470
+
471
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
472
+
473
+ if self.text_encoder_2 is not None:
474
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
475
+ else:
476
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
477
+
478
+ bs_embed, seq_len, _ = prompt_embeds.shape
479
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
480
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
481
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
482
+
483
+ if do_classifier_free_guidance:
484
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
485
+ seq_len = negative_prompt_embeds.shape[1]
486
+
487
+ if self.text_encoder_2 is not None:
488
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
489
+ else:
490
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
491
+
492
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
493
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
494
+
495
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
496
+ bs_embed * num_images_per_prompt, -1
497
+ )
498
+ if do_classifier_free_guidance:
499
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
500
+ bs_embed * num_images_per_prompt, -1
501
+ )
502
+
503
+ if self.text_encoder is not None:
504
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
505
+ # Retrieve the original scale by scaling back the LoRA layers
506
+ unscale_lora_layers(self.text_encoder, lora_scale)
507
+
508
+ if self.text_encoder_2 is not None:
509
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
510
+ # Retrieve the original scale by scaling back the LoRA layers
511
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
512
+
513
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
514
+
515
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
516
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
517
+ dtype = next(self.image_encoder.parameters()).dtype
518
+
519
+ if not isinstance(image, torch.Tensor):
520
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
521
+
522
+ image = image.to(device=device, dtype=dtype)
523
+ if output_hidden_states:
524
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
525
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
526
+ uncond_image_enc_hidden_states = self.image_encoder(
527
+ torch.zeros_like(image), output_hidden_states=True
528
+ ).hidden_states[-2]
529
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
530
+ num_images_per_prompt, dim=0
531
+ )
532
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
533
+ else:
534
+ image_embeds = self.image_encoder(image).image_embeds
535
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
536
+ uncond_image_embeds = torch.zeros_like(image_embeds)
537
+
538
+ return image_embeds, uncond_image_embeds
539
+
540
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
541
+ def prepare_ip_adapter_image_embeds(
542
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
543
+ ):
544
+ image_embeds = []
545
+ if do_classifier_free_guidance:
546
+ negative_image_embeds = []
547
+ if ip_adapter_image_embeds is None:
548
+ if not isinstance(ip_adapter_image, list):
549
+ ip_adapter_image = [ip_adapter_image]
550
+
551
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
552
+ raise ValueError(
553
+ 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."
554
+ )
555
+
556
+ for single_ip_adapter_image, image_proj_layer in zip(
557
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
558
+ ):
559
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
560
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
561
+ single_ip_adapter_image, device, 1, output_hidden_state
562
+ )
563
+
564
+ image_embeds.append(single_image_embeds[None, :])
565
+ if do_classifier_free_guidance:
566
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
567
+ else:
568
+ for single_image_embeds in ip_adapter_image_embeds:
569
+ if do_classifier_free_guidance:
570
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
571
+ negative_image_embeds.append(single_negative_image_embeds)
572
+ image_embeds.append(single_image_embeds)
573
+
574
+ ip_adapter_image_embeds = []
575
+ for i, single_image_embeds in enumerate(image_embeds):
576
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
577
+ if do_classifier_free_guidance:
578
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
579
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
580
+
581
+ single_image_embeds = single_image_embeds.to(device=device)
582
+ ip_adapter_image_embeds.append(single_image_embeds)
583
+
584
+ return ip_adapter_image_embeds
585
+
586
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
587
+ def prepare_extra_step_kwargs(self, generator, eta):
588
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
589
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
590
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
591
+ # and should be between [0, 1]
592
+
593
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
594
+ extra_step_kwargs = {}
595
+ if accepts_eta:
596
+ extra_step_kwargs["eta"] = eta
597
+
598
+ # check if the scheduler accepts generator
599
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
600
+ if accepts_generator:
601
+ extra_step_kwargs["generator"] = generator
602
+ return extra_step_kwargs
603
+
604
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.check_inputs
605
+ def check_inputs(
606
+ self,
607
+ prompt,
608
+ prompt_2,
609
+ height,
610
+ width,
611
+ callback_steps,
612
+ negative_prompt=None,
613
+ negative_prompt_2=None,
614
+ prompt_embeds=None,
615
+ negative_prompt_embeds=None,
616
+ pooled_prompt_embeds=None,
617
+ negative_pooled_prompt_embeds=None,
618
+ ip_adapter_image=None,
619
+ ip_adapter_image_embeds=None,
620
+ callback_on_step_end_tensor_inputs=None,
621
+ ):
622
+ if height % 8 != 0 or width % 8 != 0:
623
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
624
+
625
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
626
+ raise ValueError(
627
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
628
+ f" {type(callback_steps)}."
629
+ )
630
+
631
+ if callback_on_step_end_tensor_inputs is not None and not all(
632
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
633
+ ):
634
+ raise ValueError(
635
+ 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]}"
636
+ )
637
+
638
+ if prompt is not None and prompt_embeds is not None:
639
+ raise ValueError(
640
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
641
+ " only forward one of the two."
642
+ )
643
+ elif prompt_2 is not None and prompt_embeds is not None:
644
+ raise ValueError(
645
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
646
+ " only forward one of the two."
647
+ )
648
+ elif prompt is None and prompt_embeds is None:
649
+ raise ValueError(
650
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
651
+ )
652
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
653
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
654
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
655
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
656
+
657
+ if negative_prompt is not None and negative_prompt_embeds is not None:
658
+ raise ValueError(
659
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
660
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
661
+ )
662
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
663
+ raise ValueError(
664
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
665
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
666
+ )
667
+
668
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
669
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
670
+ raise ValueError(
671
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
672
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
673
+ f" {negative_prompt_embeds.shape}."
674
+ )
675
+
676
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
677
+ raise ValueError(
678
+ "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`."
679
+ )
680
+
681
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
682
+ raise ValueError(
683
+ "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`."
684
+ )
685
+
686
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
687
+ raise ValueError(
688
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
689
+ )
690
+
691
+ if ip_adapter_image_embeds is not None:
692
+ if not isinstance(ip_adapter_image_embeds, list):
693
+ raise ValueError(
694
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
695
+ )
696
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
697
+ raise ValueError(
698
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
699
+ )
700
+
701
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
702
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
703
+ shape = (
704
+ batch_size,
705
+ num_channels_latents,
706
+ int(height) // self.vae_scale_factor,
707
+ int(width) // self.vae_scale_factor,
708
+ )
709
+ if isinstance(generator, list) and len(generator) != batch_size:
710
+ raise ValueError(
711
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
712
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
713
+ )
714
+
715
+ if latents is None:
716
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
717
+ else:
718
+ latents = latents.to(device)
719
+
720
+ # scale the initial noise by the standard deviation required by the scheduler
721
+ latents = latents * self.scheduler.init_noise_sigma
722
+ return latents
723
+
724
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
725
+ def _get_add_time_ids(
726
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
727
+ ):
728
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
729
+
730
+ passed_add_embed_dim = (
731
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
732
+ )
733
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
734
+
735
+ if expected_add_embed_dim != passed_add_embed_dim:
736
+ raise ValueError(
737
+ 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`."
738
+ )
739
+
740
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
741
+ return add_time_ids
742
+
743
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.upcast_vae
744
+ def upcast_vae(self):
745
+ dtype = self.vae.dtype
746
+ self.vae.to(dtype=torch.float32)
747
+ use_torch_2_0_or_xformers = isinstance(
748
+ self.vae.decoder.mid_block.attentions[0].processor,
749
+ (
750
+ AttnProcessor2_0,
751
+ XFormersAttnProcessor,
752
+ FusedAttnProcessor2_0,
753
+ ),
754
+ )
755
+ # if xformers or torch_2_0 is used attention block does not need
756
+ # to be in float32 which can save lots of memory
757
+ if use_torch_2_0_or_xformers:
758
+ self.vae.post_quant_conv.to(dtype)
759
+ self.vae.decoder.conv_in.to(dtype)
760
+ self.vae.decoder.mid_block.to(dtype)
761
+
762
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
763
+ def get_guidance_scale_embedding(
764
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
765
+ ) -> torch.Tensor:
766
+ """
767
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
768
+
769
+ Args:
770
+ w (`torch.Tensor`):
771
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
772
+ embedding_dim (`int`, *optional*, defaults to 512):
773
+ Dimension of the embeddings to generate.
774
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
775
+ Data type of the generated embeddings.
776
+
777
+ Returns:
778
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
779
+ """
780
+ assert len(w.shape) == 1
781
+ w = w * 1000.0
782
+
783
+ half_dim = embedding_dim // 2
784
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
785
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
786
+ emb = w.to(dtype)[:, None] * emb[None, :]
787
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
788
+ if embedding_dim % 2 == 1: # zero pad
789
+ emb = torch.nn.functional.pad(emb, (0, 1))
790
+ assert emb.shape == (w.shape[0], embedding_dim)
791
+ return emb
792
+
793
+ @property
794
+ def guidance_scale(self):
795
+ return self._guidance_scale
796
+
797
+ @property
798
+ def guidance_rescale(self):
799
+ return self._guidance_rescale
800
+
801
+ @property
802
+ def clip_skip(self):
803
+ return self._clip_skip
804
+
805
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
806
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
807
+ # corresponds to doing no classifier free guidance.
808
+ @property
809
+ def do_classifier_free_guidance(self):
810
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
811
+
812
+ @property
813
+ def cross_attention_kwargs(self):
814
+ return self._cross_attention_kwargs
815
+
816
+ @property
817
+ def denoising_end(self):
818
+ return self._denoising_end
819
+
820
+ @property
821
+ def num_timesteps(self):
822
+ return self._num_timesteps
823
+
824
+ @property
825
+ def interrupt(self):
826
+ return self._interrupt
827
+
828
+ @torch.no_grad()
829
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
830
+ def __call__(
831
+ self,
832
+ prompt: Union[str, List[str]] = None,
833
+ prompt_2: Optional[Union[str, List[str]]] = None,
834
+ height: Optional[int] = None,
835
+ width: Optional[int] = None,
836
+ num_inference_steps: int = 50,
837
+ timesteps: List[int] = None,
838
+ sigmas: List[float] = None,
839
+ denoising_end: Optional[float] = None,
840
+ guidance_scale: float = 5.0,
841
+ negative_prompt: Optional[Union[str, List[str]]] = None,
842
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
843
+ num_images_per_prompt: Optional[int] = 1,
844
+ eta: float = 0.0,
845
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
846
+ latents: Optional[torch.Tensor] = None,
847
+ prompt_embeds: Optional[torch.Tensor] = None,
848
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
849
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
850
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
851
+ ip_adapter_image: Optional[PipelineImageInput] = None,
852
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
853
+ output_type: Optional[str] = "pil",
854
+ return_dict: bool = True,
855
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
856
+ guidance_rescale: float = 0.0,
857
+ original_size: Optional[Tuple[int, int]] = None,
858
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
859
+ target_size: Optional[Tuple[int, int]] = None,
860
+ negative_original_size: Optional[Tuple[int, int]] = None,
861
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
862
+ negative_target_size: Optional[Tuple[int, int]] = None,
863
+ clip_skip: Optional[int] = None,
864
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
865
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
866
+ pag_scale: float = 3.0,
867
+ pag_adaptive_scale: float = 0.0,
868
+ ):
869
+ r"""
870
+ Function invoked when calling the pipeline for generation.
871
+
872
+ Args:
873
+ prompt (`str` or `List[str]`, *optional*):
874
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
875
+ instead.
876
+ prompt_2 (`str` or `List[str]`, *optional*):
877
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
878
+ used in both text-encoders
879
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
880
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
881
+ Anything below 512 pixels won't work well for
882
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
883
+ and checkpoints that are not specifically fine-tuned on low resolutions.
884
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
885
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
886
+ Anything below 512 pixels won't work well for
887
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
888
+ and checkpoints that are not specifically fine-tuned on low resolutions.
889
+ num_inference_steps (`int`, *optional*, defaults to 50):
890
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
891
+ expense of slower inference.
892
+ timesteps (`List[int]`, *optional*):
893
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
894
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
895
+ passed will be used. Must be in descending order.
896
+ sigmas (`List[float]`, *optional*):
897
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
898
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
899
+ will be used.
900
+ denoising_end (`float`, *optional*):
901
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
902
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
903
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
904
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
905
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
906
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
907
+ guidance_scale (`float`, *optional*, defaults to 5.0):
908
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
909
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
910
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
911
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
912
+ usually at the expense of lower image quality.
913
+ negative_prompt (`str` or `List[str]`, *optional*):
914
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
915
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
916
+ less than `1`).
917
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
918
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
919
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
920
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
921
+ The number of images to generate per prompt.
922
+ eta (`float`, *optional*, defaults to 0.0):
923
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
924
+ [`schedulers.DDIMScheduler`], will be ignored for others.
925
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
926
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
927
+ to make generation deterministic.
928
+ latents (`torch.Tensor`, *optional*):
929
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
930
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
931
+ tensor will ge generated by sampling using the supplied random `generator`.
932
+ prompt_embeds (`torch.Tensor`, *optional*):
933
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
934
+ provided, text embeddings will be generated from `prompt` input argument.
935
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
936
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
937
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
938
+ argument.
939
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
940
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
941
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
942
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
943
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
944
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
945
+ input argument.
946
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
947
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
948
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
949
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
950
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
951
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
952
+ output_type (`str`, *optional*, defaults to `"pil"`):
953
+ The output format of the generate image. Choose between
954
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
955
+ return_dict (`bool`, *optional*, defaults to `True`):
956
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
957
+ of a plain tuple.
958
+ cross_attention_kwargs (`dict`, *optional*):
959
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
960
+ `self.processor` in
961
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
962
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
963
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
964
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
965
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
966
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
967
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
968
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
969
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
970
+ explained in section 2.2 of
971
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
972
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
973
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
974
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
975
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
976
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
977
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
978
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
979
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
980
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
981
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
982
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
983
+ micro-conditioning as explained in section 2.2 of
984
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
985
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
986
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
987
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
988
+ micro-conditioning as explained in section 2.2 of
989
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
990
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
991
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
992
+ To negatively condition the generation process based on a target image resolution. It should be as same
993
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
994
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
995
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
996
+ callback_on_step_end (`Callable`, *optional*):
997
+ A function that calls at the end of each denoising steps during the inference. The function is called
998
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
999
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1000
+ `callback_on_step_end_tensor_inputs`.
1001
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1002
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1003
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1004
+ `._callback_tensor_inputs` attribute of your pipeline class.
1005
+ pag_scale (`float`, *optional*, defaults to 3.0):
1006
+ The scale factor for the perturbed attention guidance. If it is set to 0.0, the perturbed attention
1007
+ guidance will not be used.
1008
+ pag_adaptive_scale (`float`, *optional*, defaults to 0.0):
1009
+ The adaptive scale factor for the perturbed attention guidance. If it is set to 0.0, `pag_scale` is
1010
+ used.
1011
+
1012
+ Examples:
1013
+
1014
+ Returns:
1015
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1016
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1017
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1018
+ """
1019
+
1020
+ # 0. Default height and width to unet
1021
+ height = height or self.default_sample_size * self.vae_scale_factor
1022
+ width = width or self.default_sample_size * self.vae_scale_factor
1023
+
1024
+ original_size = original_size or (height, width)
1025
+ target_size = target_size or (height, width)
1026
+
1027
+ # 1. Check inputs. Raise error if not correct
1028
+ self.check_inputs(
1029
+ prompt,
1030
+ prompt_2,
1031
+ height,
1032
+ width,
1033
+ None,
1034
+ negative_prompt,
1035
+ negative_prompt_2,
1036
+ prompt_embeds,
1037
+ negative_prompt_embeds,
1038
+ pooled_prompt_embeds,
1039
+ negative_pooled_prompt_embeds,
1040
+ ip_adapter_image,
1041
+ ip_adapter_image_embeds,
1042
+ callback_on_step_end_tensor_inputs,
1043
+ )
1044
+
1045
+ self._guidance_scale = guidance_scale
1046
+ self._guidance_rescale = guidance_rescale
1047
+ self._clip_skip = clip_skip
1048
+ self._cross_attention_kwargs = cross_attention_kwargs
1049
+ self._denoising_end = denoising_end
1050
+ self._interrupt = False
1051
+ self._pag_scale = pag_scale
1052
+ self._pag_adaptive_scale = pag_adaptive_scale
1053
+
1054
+ # 2. Define call parameters
1055
+ if prompt is not None and isinstance(prompt, str):
1056
+ batch_size = 1
1057
+ elif prompt is not None and isinstance(prompt, list):
1058
+ batch_size = len(prompt)
1059
+ else:
1060
+ batch_size = prompt_embeds.shape[0]
1061
+
1062
+ device = self._execution_device
1063
+
1064
+ # 3. Encode input prompt
1065
+ lora_scale = (
1066
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1067
+ )
1068
+
1069
+ (
1070
+ prompt_embeds,
1071
+ negative_prompt_embeds,
1072
+ pooled_prompt_embeds,
1073
+ negative_pooled_prompt_embeds,
1074
+ ) = self.encode_prompt(
1075
+ prompt=prompt,
1076
+ prompt_2=prompt_2,
1077
+ device=device,
1078
+ num_images_per_prompt=num_images_per_prompt,
1079
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1080
+ negative_prompt=negative_prompt,
1081
+ negative_prompt_2=negative_prompt_2,
1082
+ prompt_embeds=prompt_embeds,
1083
+ negative_prompt_embeds=negative_prompt_embeds,
1084
+ pooled_prompt_embeds=pooled_prompt_embeds,
1085
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1086
+ lora_scale=lora_scale,
1087
+ clip_skip=self.clip_skip,
1088
+ )
1089
+
1090
+ # 4. Prepare timesteps
1091
+ timesteps, num_inference_steps = retrieve_timesteps(
1092
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1093
+ )
1094
+
1095
+ # 5. Prepare latent variables
1096
+ num_channels_latents = self.unet.config.in_channels
1097
+ latents = self.prepare_latents(
1098
+ batch_size * num_images_per_prompt,
1099
+ num_channels_latents,
1100
+ height,
1101
+ width,
1102
+ prompt_embeds.dtype,
1103
+ device,
1104
+ generator,
1105
+ latents,
1106
+ )
1107
+
1108
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1109
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1110
+
1111
+ # 7. Prepare added time ids & embeddings
1112
+ add_text_embeds = pooled_prompt_embeds
1113
+ if self.text_encoder_2 is None:
1114
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1115
+ else:
1116
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1117
+
1118
+ add_time_ids = self._get_add_time_ids(
1119
+ original_size,
1120
+ crops_coords_top_left,
1121
+ target_size,
1122
+ dtype=prompt_embeds.dtype,
1123
+ text_encoder_projection_dim=text_encoder_projection_dim,
1124
+ )
1125
+ if negative_original_size is not None and negative_target_size is not None:
1126
+ negative_add_time_ids = self._get_add_time_ids(
1127
+ negative_original_size,
1128
+ negative_crops_coords_top_left,
1129
+ negative_target_size,
1130
+ dtype=prompt_embeds.dtype,
1131
+ text_encoder_projection_dim=text_encoder_projection_dim,
1132
+ )
1133
+ else:
1134
+ negative_add_time_ids = add_time_ids
1135
+
1136
+ if self.do_perturbed_attention_guidance:
1137
+ prompt_embeds = self._prepare_perturbed_attention_guidance(
1138
+ prompt_embeds, negative_prompt_embeds, self.do_classifier_free_guidance
1139
+ )
1140
+ add_text_embeds = self._prepare_perturbed_attention_guidance(
1141
+ add_text_embeds, negative_pooled_prompt_embeds, self.do_classifier_free_guidance
1142
+ )
1143
+ add_time_ids = self._prepare_perturbed_attention_guidance(
1144
+ add_time_ids, negative_add_time_ids, self.do_classifier_free_guidance
1145
+ )
1146
+
1147
+ elif self.do_classifier_free_guidance:
1148
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1149
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1150
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1151
+
1152
+ prompt_embeds = prompt_embeds.to(device)
1153
+ add_text_embeds = add_text_embeds.to(device)
1154
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1155
+
1156
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1157
+ ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
1158
+ ip_adapter_image,
1159
+ ip_adapter_image_embeds,
1160
+ device,
1161
+ batch_size * num_images_per_prompt,
1162
+ self.do_classifier_free_guidance,
1163
+ )
1164
+
1165
+ for i, image_embeds in enumerate(ip_adapter_image_embeds):
1166
+ negative_image_embeds = None
1167
+ if self.do_classifier_free_guidance:
1168
+ negative_image_embeds, image_embeds = image_embeds.chunk(2)
1169
+
1170
+ if self.do_perturbed_attention_guidance:
1171
+ image_embeds = self._prepare_perturbed_attention_guidance(
1172
+ image_embeds, negative_image_embeds, self.do_classifier_free_guidance
1173
+ )
1174
+ elif self.do_classifier_free_guidance:
1175
+ image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0)
1176
+ image_embeds = image_embeds.to(device)
1177
+ ip_adapter_image_embeds[i] = image_embeds
1178
+
1179
+ # 8. Denoising loop
1180
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1181
+
1182
+ # 8.1 Apply denoising_end
1183
+ if (
1184
+ self.denoising_end is not None
1185
+ and isinstance(self.denoising_end, float)
1186
+ and self.denoising_end > 0
1187
+ and self.denoising_end < 1
1188
+ ):
1189
+ discrete_timestep_cutoff = int(
1190
+ round(
1191
+ self.scheduler.config.num_train_timesteps
1192
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1193
+ )
1194
+ )
1195
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1196
+ timesteps = timesteps[:num_inference_steps]
1197
+
1198
+ # 9. Optionally get Guidance Scale Embedding
1199
+ timestep_cond = None
1200
+ if self.unet.config.time_cond_proj_dim is not None:
1201
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1202
+ timestep_cond = self.get_guidance_scale_embedding(
1203
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1204
+ ).to(device=device, dtype=latents.dtype)
1205
+
1206
+ if self.do_perturbed_attention_guidance:
1207
+ original_attn_proc = self.unet.attn_processors
1208
+ self._set_pag_attn_processor(
1209
+ pag_applied_layers=self.pag_applied_layers,
1210
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1211
+ )
1212
+
1213
+ self._num_timesteps = len(timesteps)
1214
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1215
+ for i, t in enumerate(timesteps):
1216
+ if self.interrupt:
1217
+ continue
1218
+
1219
+ # expand the latents if we are doing classifier free guidance, perturbed-attention guidance, or both
1220
+ latent_model_input = torch.cat([latents] * (prompt_embeds.shape[0] // latents.shape[0]))
1221
+
1222
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1223
+
1224
+ # predict the noise residual
1225
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1226
+ if ip_adapter_image_embeds is not None:
1227
+ added_cond_kwargs["image_embeds"] = ip_adapter_image_embeds
1228
+ noise_pred = self.unet(
1229
+ latent_model_input,
1230
+ t,
1231
+ encoder_hidden_states=prompt_embeds,
1232
+ timestep_cond=timestep_cond,
1233
+ cross_attention_kwargs=self.cross_attention_kwargs,
1234
+ added_cond_kwargs=added_cond_kwargs,
1235
+ return_dict=False,
1236
+ )[0]
1237
+
1238
+ # perform guidance
1239
+ if self.do_perturbed_attention_guidance:
1240
+ noise_pred = self._apply_perturbed_attention_guidance(
1241
+ noise_pred, self.do_classifier_free_guidance, self.guidance_scale, t
1242
+ )
1243
+
1244
+ elif self.do_classifier_free_guidance:
1245
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1246
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1247
+
1248
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1249
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1250
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1251
+
1252
+ # compute the previous noisy sample x_t -> x_t-1
1253
+ latents_dtype = latents.dtype
1254
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1255
+ if latents.dtype != latents_dtype:
1256
+ if torch.backends.mps.is_available():
1257
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1258
+ latents = latents.to(latents_dtype)
1259
+
1260
+ if callback_on_step_end is not None:
1261
+ callback_kwargs = {}
1262
+ for k in callback_on_step_end_tensor_inputs:
1263
+ callback_kwargs[k] = locals()[k]
1264
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1265
+
1266
+ latents = callback_outputs.pop("latents", latents)
1267
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1268
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1269
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1270
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1271
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1272
+ )
1273
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1274
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1275
+
1276
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1277
+ progress_bar.update()
1278
+
1279
+ if XLA_AVAILABLE:
1280
+ xm.mark_step()
1281
+
1282
+ if not output_type == "latent":
1283
+ # make sure the VAE is in float32 mode, as it overflows in float16
1284
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1285
+
1286
+ if needs_upcasting:
1287
+ self.upcast_vae()
1288
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1289
+ elif latents.dtype != self.vae.dtype:
1290
+ if torch.backends.mps.is_available():
1291
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1292
+ self.vae = self.vae.to(latents.dtype)
1293
+
1294
+ # unscale/denormalize the latents
1295
+ # denormalize with the mean and std if available and not None
1296
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1297
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1298
+ if has_latents_mean and has_latents_std:
1299
+ latents_mean = (
1300
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1301
+ )
1302
+ latents_std = (
1303
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1304
+ )
1305
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1306
+ else:
1307
+ latents = latents / self.vae.config.scaling_factor
1308
+
1309
+ image = self.vae.decode(latents, return_dict=False)[0]
1310
+
1311
+ # cast back to fp16 if needed
1312
+ if needs_upcasting:
1313
+ self.vae.to(dtype=torch.float16)
1314
+ else:
1315
+ image = latents
1316
+
1317
+ if not output_type == "latent":
1318
+ # apply watermark if available
1319
+ if self.watermark is not None:
1320
+ image = self.watermark.apply_watermark(image)
1321
+
1322
+ image = self.image_processor.postprocess(image, output_type=output_type)
1323
+
1324
+ # Offload all models
1325
+ self.maybe_free_model_hooks()
1326
+
1327
+ if self.do_perturbed_attention_guidance:
1328
+ self.unet.set_attn_processor(original_attn_proc)
1329
+
1330
+ if not return_dict:
1331
+ return (image,)
1332
+
1333
+ return StableDiffusionXLPipelineOutput(images=image)