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