diffusers 0.29.2__py3-none-any.whl → 0.30.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. diffusers/__init__.py +94 -3
  2. diffusers/commands/env.py +1 -5
  3. diffusers/configuration_utils.py +4 -9
  4. diffusers/dependency_versions_table.py +2 -2
  5. diffusers/image_processor.py +1 -2
  6. diffusers/loaders/__init__.py +17 -2
  7. diffusers/loaders/ip_adapter.py +10 -7
  8. diffusers/loaders/lora_base.py +752 -0
  9. diffusers/loaders/lora_pipeline.py +2222 -0
  10. diffusers/loaders/peft.py +213 -5
  11. diffusers/loaders/single_file.py +1 -12
  12. diffusers/loaders/single_file_model.py +31 -10
  13. diffusers/loaders/single_file_utils.py +262 -2
  14. diffusers/loaders/textual_inversion.py +1 -6
  15. diffusers/loaders/unet.py +23 -208
  16. diffusers/models/__init__.py +20 -0
  17. diffusers/models/activations.py +22 -0
  18. diffusers/models/attention.py +386 -7
  19. diffusers/models/attention_processor.py +1795 -629
  20. diffusers/models/autoencoders/__init__.py +2 -0
  21. diffusers/models/autoencoders/autoencoder_kl.py +14 -3
  22. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1035 -0
  23. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
  24. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  25. diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
  26. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  27. diffusers/models/autoencoders/vq_model.py +4 -4
  28. diffusers/models/controlnet.py +2 -3
  29. diffusers/models/controlnet_hunyuan.py +401 -0
  30. diffusers/models/controlnet_sd3.py +11 -11
  31. diffusers/models/controlnet_sparsectrl.py +789 -0
  32. diffusers/models/controlnet_xs.py +40 -10
  33. diffusers/models/downsampling.py +68 -0
  34. diffusers/models/embeddings.py +319 -36
  35. diffusers/models/model_loading_utils.py +1 -3
  36. diffusers/models/modeling_flax_utils.py +1 -6
  37. diffusers/models/modeling_utils.py +4 -16
  38. diffusers/models/normalization.py +203 -12
  39. diffusers/models/transformers/__init__.py +6 -0
  40. diffusers/models/transformers/auraflow_transformer_2d.py +527 -0
  41. diffusers/models/transformers/cogvideox_transformer_3d.py +345 -0
  42. diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
  43. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  44. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  45. diffusers/models/transformers/pixart_transformer_2d.py +102 -1
  46. diffusers/models/transformers/prior_transformer.py +1 -1
  47. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  48. diffusers/models/transformers/transformer_flux.py +455 -0
  49. diffusers/models/transformers/transformer_sd3.py +18 -4
  50. diffusers/models/unets/unet_1d_blocks.py +1 -1
  51. diffusers/models/unets/unet_2d_condition.py +8 -1
  52. diffusers/models/unets/unet_3d_blocks.py +51 -920
  53. diffusers/models/unets/unet_3d_condition.py +4 -1
  54. diffusers/models/unets/unet_i2vgen_xl.py +4 -1
  55. diffusers/models/unets/unet_kandinsky3.py +1 -1
  56. diffusers/models/unets/unet_motion_model.py +1330 -84
  57. diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
  58. diffusers/models/unets/unet_stable_cascade.py +1 -3
  59. diffusers/models/unets/uvit_2d.py +1 -1
  60. diffusers/models/upsampling.py +64 -0
  61. diffusers/models/vq_model.py +8 -4
  62. diffusers/optimization.py +1 -1
  63. diffusers/pipelines/__init__.py +100 -3
  64. diffusers/pipelines/animatediff/__init__.py +4 -0
  65. diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
  66. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
  67. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
  68. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
  69. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
  70. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  71. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
  72. diffusers/pipelines/aura_flow/__init__.py +48 -0
  73. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
  74. diffusers/pipelines/auto_pipeline.py +97 -19
  75. diffusers/pipelines/cogvideo/__init__.py +48 -0
  76. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +687 -0
  77. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  78. diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
  79. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
  80. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
  81. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
  82. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
  83. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
  84. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  85. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  86. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
  87. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
  88. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
  89. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
  90. diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
  91. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
  92. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
  93. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
  94. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
  95. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
  96. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
  97. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
  98. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  100. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
  101. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
  102. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
  103. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  104. diffusers/pipelines/flux/__init__.py +47 -0
  105. diffusers/pipelines/flux/pipeline_flux.py +749 -0
  106. diffusers/pipelines/flux/pipeline_output.py +21 -0
  107. diffusers/pipelines/free_init_utils.py +2 -0
  108. diffusers/pipelines/free_noise_utils.py +236 -0
  109. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
  110. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
  111. diffusers/pipelines/kolors/__init__.py +54 -0
  112. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  113. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
  114. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  115. diffusers/pipelines/kolors/text_encoder.py +889 -0
  116. diffusers/pipelines/kolors/tokenizer.py +334 -0
  117. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
  118. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
  119. diffusers/pipelines/latte/__init__.py +48 -0
  120. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  121. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
  122. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
  123. diffusers/pipelines/lumina/__init__.py +48 -0
  124. diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
  125. diffusers/pipelines/pag/__init__.py +67 -0
  126. diffusers/pipelines/pag/pag_utils.py +237 -0
  127. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
  128. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
  129. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
  130. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  131. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
  132. diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
  133. diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
  134. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
  135. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
  136. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
  137. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
  138. diffusers/pipelines/pia/pipeline_pia.py +30 -37
  139. diffusers/pipelines/pipeline_flax_utils.py +4 -9
  140. diffusers/pipelines/pipeline_loading_utils.py +0 -3
  141. diffusers/pipelines/pipeline_utils.py +2 -14
  142. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
  143. diffusers/pipelines/stable_audio/__init__.py +50 -0
  144. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  145. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
  146. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
  147. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
  151. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
  152. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
  153. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
  154. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
  155. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
  156. diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
  157. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
  158. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
  159. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
  160. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
  161. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
  162. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
  163. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
  164. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
  165. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
  166. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
  167. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
  168. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
  171. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
  172. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
  175. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
  179. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  180. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  181. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
  182. diffusers/schedulers/__init__.py +8 -0
  183. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  184. diffusers/schedulers/scheduling_ddim.py +1 -1
  185. diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
  186. diffusers/schedulers/scheduling_ddpm.py +1 -1
  187. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
  188. diffusers/schedulers/scheduling_deis_multistep.py +2 -2
  189. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  190. diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
  191. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
  192. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
  193. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
  194. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
  195. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
  196. diffusers/schedulers/scheduling_ipndm.py +1 -1
  197. diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
  198. diffusers/schedulers/scheduling_utils.py +1 -3
  199. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  200. diffusers/training_utils.py +99 -14
  201. diffusers/utils/__init__.py +2 -2
  202. diffusers/utils/dummy_pt_objects.py +210 -0
  203. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  204. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  205. diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
  206. diffusers/utils/dynamic_modules_utils.py +1 -11
  207. diffusers/utils/export_utils.py +1 -4
  208. diffusers/utils/hub_utils.py +45 -42
  209. diffusers/utils/import_utils.py +19 -16
  210. diffusers/utils/loading_utils.py +76 -3
  211. diffusers/utils/testing_utils.py +11 -8
  212. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/METADATA +73 -83
  213. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/RECORD +217 -164
  214. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/WHEEL +1 -1
  215. diffusers/loaders/autoencoder.py +0 -146
  216. diffusers/loaders/controlnet.py +0 -136
  217. diffusers/loaders/lora.py +0 -1728
  218. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/LICENSE +0 -0
  219. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/entry_points.txt +0 -0
  220. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1050 @@
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
+ import inspect
15
+ from typing import Any, Callable, Dict, List, Optional, Union
16
+
17
+ import torch
18
+ from packaging import version
19
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
20
+
21
+ from ...configuration_utils import FrozenDict
22
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
23
+ from ...loaders import FromSingleFileMixin, IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
24
+ from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
25
+ from ...models.lora import adjust_lora_scale_text_encoder
26
+ from ...schedulers import KarrasDiffusionSchedulers
27
+ from ...utils import (
28
+ USE_PEFT_BACKEND,
29
+ deprecate,
30
+ logging,
31
+ replace_example_docstring,
32
+ scale_lora_layers,
33
+ unscale_lora_layers,
34
+ )
35
+ from ...utils.torch_utils import randn_tensor
36
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
37
+ from ..stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
38
+ from ..stable_diffusion.safety_checker import StableDiffusionSafetyChecker
39
+ from .pag_utils import PAGMixin
40
+
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ EXAMPLE_DOC_STRING = """
45
+ Examples:
46
+ ```py
47
+ >>> import torch
48
+ >>> from diffusers import AutoPipelineForText2Image
49
+
50
+ >>> pipe = AutoPipelineForText2Image.from_pretrained(
51
+ ... "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
52
+ ... )
53
+ >>> pipe = pipe.to("cuda")
54
+
55
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
56
+ >>> image = pipe(prompt, pag_scale=0.3).images[0]
57
+ ```
58
+ """
59
+
60
+
61
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
62
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
63
+ """
64
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
65
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
66
+ """
67
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
68
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
69
+ # rescale the results from guidance (fixes overexposure)
70
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
71
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
72
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
73
+ return noise_cfg
74
+
75
+
76
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
77
+ def retrieve_timesteps(
78
+ scheduler,
79
+ num_inference_steps: Optional[int] = None,
80
+ device: Optional[Union[str, torch.device]] = None,
81
+ timesteps: Optional[List[int]] = None,
82
+ sigmas: Optional[List[float]] = None,
83
+ **kwargs,
84
+ ):
85
+ """
86
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
87
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
88
+
89
+ Args:
90
+ scheduler (`SchedulerMixin`):
91
+ The scheduler to get timesteps from.
92
+ num_inference_steps (`int`):
93
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
94
+ must be `None`.
95
+ device (`str` or `torch.device`, *optional*):
96
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
97
+ timesteps (`List[int]`, *optional*):
98
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
99
+ `num_inference_steps` and `sigmas` must be `None`.
100
+ sigmas (`List[float]`, *optional*):
101
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
102
+ `num_inference_steps` and `timesteps` must be `None`.
103
+
104
+ Returns:
105
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
106
+ second element is the number of inference steps.
107
+ """
108
+ if timesteps is not None and sigmas is not None:
109
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
110
+ if timesteps is not None:
111
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
112
+ if not accepts_timesteps:
113
+ raise ValueError(
114
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
115
+ f" timestep schedules. Please check whether you are using the correct scheduler."
116
+ )
117
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
118
+ timesteps = scheduler.timesteps
119
+ num_inference_steps = len(timesteps)
120
+ elif sigmas is not None:
121
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
122
+ if not accept_sigmas:
123
+ raise ValueError(
124
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
125
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
126
+ )
127
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
128
+ timesteps = scheduler.timesteps
129
+ num_inference_steps = len(timesteps)
130
+ else:
131
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
132
+ timesteps = scheduler.timesteps
133
+ return timesteps, num_inference_steps
134
+
135
+
136
+ class StableDiffusionPAGPipeline(
137
+ DiffusionPipeline,
138
+ StableDiffusionMixin,
139
+ TextualInversionLoaderMixin,
140
+ StableDiffusionLoraLoaderMixin,
141
+ IPAdapterMixin,
142
+ FromSingleFileMixin,
143
+ PAGMixin,
144
+ ):
145
+ r"""
146
+ Pipeline for text-to-image generation using Stable Diffusion.
147
+
148
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
149
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
150
+
151
+ The pipeline also inherits the following loading methods:
152
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
153
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
154
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
155
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
156
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
157
+
158
+ Args:
159
+ vae ([`AutoencoderKL`]):
160
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
161
+ text_encoder ([`~transformers.CLIPTextModel`]):
162
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
163
+ tokenizer ([`~transformers.CLIPTokenizer`]):
164
+ A `CLIPTokenizer` to tokenize text.
165
+ unet ([`UNet2DConditionModel`]):
166
+ A `UNet2DConditionModel` to denoise the encoded image latents.
167
+ scheduler ([`SchedulerMixin`]):
168
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
169
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
170
+ safety_checker ([`StableDiffusionSafetyChecker`]):
171
+ Classification module that estimates whether generated images could be considered offensive or harmful.
172
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
173
+ about a model's potential harms.
174
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
175
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
176
+ """
177
+
178
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
179
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
180
+ _exclude_from_cpu_offload = ["safety_checker"]
181
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
182
+
183
+ def __init__(
184
+ self,
185
+ vae: AutoencoderKL,
186
+ text_encoder: CLIPTextModel,
187
+ tokenizer: CLIPTokenizer,
188
+ unet: UNet2DConditionModel,
189
+ scheduler: KarrasDiffusionSchedulers,
190
+ safety_checker: StableDiffusionSafetyChecker,
191
+ feature_extractor: CLIPImageProcessor,
192
+ image_encoder: CLIPVisionModelWithProjection = None,
193
+ requires_safety_checker: bool = True,
194
+ pag_applied_layers: Union[str, List[str]] = "mid",
195
+ ):
196
+ super().__init__()
197
+
198
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
199
+ deprecation_message = (
200
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
201
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
202
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
203
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
204
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
205
+ " file"
206
+ )
207
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
208
+ new_config = dict(scheduler.config)
209
+ new_config["steps_offset"] = 1
210
+ scheduler._internal_dict = FrozenDict(new_config)
211
+
212
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
213
+ deprecation_message = (
214
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
215
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
216
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
217
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
218
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
219
+ )
220
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
221
+ new_config = dict(scheduler.config)
222
+ new_config["clip_sample"] = False
223
+ scheduler._internal_dict = FrozenDict(new_config)
224
+
225
+ if safety_checker is None and requires_safety_checker:
226
+ logger.warning(
227
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
228
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
229
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
230
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
231
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
232
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
233
+ )
234
+
235
+ if safety_checker is not None and feature_extractor is None:
236
+ raise ValueError(
237
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
238
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
239
+ )
240
+
241
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
242
+ version.parse(unet.config._diffusers_version).base_version
243
+ ) < version.parse("0.9.0.dev0")
244
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
245
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
246
+ deprecation_message = (
247
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
248
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
249
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
250
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
251
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
252
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
253
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
254
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
255
+ " the `unet/config.json` file"
256
+ )
257
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
258
+ new_config = dict(unet.config)
259
+ new_config["sample_size"] = 64
260
+ unet._internal_dict = FrozenDict(new_config)
261
+
262
+ self.register_modules(
263
+ vae=vae,
264
+ text_encoder=text_encoder,
265
+ tokenizer=tokenizer,
266
+ unet=unet,
267
+ scheduler=scheduler,
268
+ safety_checker=safety_checker,
269
+ feature_extractor=feature_extractor,
270
+ image_encoder=image_encoder,
271
+ )
272
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
273
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
274
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
275
+
276
+ self.set_pag_applied_layers(pag_applied_layers)
277
+
278
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
279
+ def encode_prompt(
280
+ self,
281
+ prompt,
282
+ device,
283
+ num_images_per_prompt,
284
+ do_classifier_free_guidance,
285
+ negative_prompt=None,
286
+ prompt_embeds: Optional[torch.Tensor] = None,
287
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
288
+ lora_scale: Optional[float] = None,
289
+ clip_skip: Optional[int] = None,
290
+ ):
291
+ r"""
292
+ Encodes the prompt into text encoder hidden states.
293
+
294
+ Args:
295
+ prompt (`str` or `List[str]`, *optional*):
296
+ prompt to be encoded
297
+ device: (`torch.device`):
298
+ torch device
299
+ num_images_per_prompt (`int`):
300
+ number of images that should be generated per prompt
301
+ do_classifier_free_guidance (`bool`):
302
+ whether to use classifier free guidance or not
303
+ negative_prompt (`str` or `List[str]`, *optional*):
304
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
305
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
306
+ less than `1`).
307
+ prompt_embeds (`torch.Tensor`, *optional*):
308
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
309
+ provided, text embeddings will be generated from `prompt` input argument.
310
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
311
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
312
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
313
+ argument.
314
+ lora_scale (`float`, *optional*):
315
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
316
+ clip_skip (`int`, *optional*):
317
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
318
+ the output of the pre-final layer will be used for computing the prompt embeddings.
319
+ """
320
+ # set lora scale so that monkey patched LoRA
321
+ # function of text encoder can correctly access it
322
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
323
+ self._lora_scale = lora_scale
324
+
325
+ # dynamically adjust the LoRA scale
326
+ if not USE_PEFT_BACKEND:
327
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
328
+ else:
329
+ scale_lora_layers(self.text_encoder, lora_scale)
330
+
331
+ if prompt is not None and isinstance(prompt, str):
332
+ batch_size = 1
333
+ elif prompt is not None and isinstance(prompt, list):
334
+ batch_size = len(prompt)
335
+ else:
336
+ batch_size = prompt_embeds.shape[0]
337
+
338
+ if prompt_embeds is None:
339
+ # textual inversion: process multi-vector tokens if necessary
340
+ if isinstance(self, TextualInversionLoaderMixin):
341
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
342
+
343
+ text_inputs = self.tokenizer(
344
+ prompt,
345
+ padding="max_length",
346
+ max_length=self.tokenizer.model_max_length,
347
+ truncation=True,
348
+ return_tensors="pt",
349
+ )
350
+ text_input_ids = text_inputs.input_ids
351
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
352
+
353
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
354
+ text_input_ids, untruncated_ids
355
+ ):
356
+ removed_text = self.tokenizer.batch_decode(
357
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
358
+ )
359
+ logger.warning(
360
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
361
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
362
+ )
363
+
364
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
365
+ attention_mask = text_inputs.attention_mask.to(device)
366
+ else:
367
+ attention_mask = None
368
+
369
+ if clip_skip is None:
370
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
371
+ prompt_embeds = prompt_embeds[0]
372
+ else:
373
+ prompt_embeds = self.text_encoder(
374
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
375
+ )
376
+ # Access the `hidden_states` first, that contains a tuple of
377
+ # all the hidden states from the encoder layers. Then index into
378
+ # the tuple to access the hidden states from the desired layer.
379
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
380
+ # We also need to apply the final LayerNorm here to not mess with the
381
+ # representations. The `last_hidden_states` that we typically use for
382
+ # obtaining the final prompt representations passes through the LayerNorm
383
+ # layer.
384
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
385
+
386
+ if self.text_encoder is not None:
387
+ prompt_embeds_dtype = self.text_encoder.dtype
388
+ elif self.unet is not None:
389
+ prompt_embeds_dtype = self.unet.dtype
390
+ else:
391
+ prompt_embeds_dtype = prompt_embeds.dtype
392
+
393
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
394
+
395
+ bs_embed, seq_len, _ = prompt_embeds.shape
396
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
397
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
398
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
399
+
400
+ # get unconditional embeddings for classifier free guidance
401
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
402
+ uncond_tokens: List[str]
403
+ if negative_prompt is None:
404
+ uncond_tokens = [""] * batch_size
405
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
406
+ raise TypeError(
407
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
408
+ f" {type(prompt)}."
409
+ )
410
+ elif isinstance(negative_prompt, str):
411
+ uncond_tokens = [negative_prompt]
412
+ elif batch_size != len(negative_prompt):
413
+ raise ValueError(
414
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
415
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
416
+ " the batch size of `prompt`."
417
+ )
418
+ else:
419
+ uncond_tokens = negative_prompt
420
+
421
+ # textual inversion: process multi-vector tokens if necessary
422
+ if isinstance(self, TextualInversionLoaderMixin):
423
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
424
+
425
+ max_length = prompt_embeds.shape[1]
426
+ uncond_input = self.tokenizer(
427
+ uncond_tokens,
428
+ padding="max_length",
429
+ max_length=max_length,
430
+ truncation=True,
431
+ return_tensors="pt",
432
+ )
433
+
434
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
435
+ attention_mask = uncond_input.attention_mask.to(device)
436
+ else:
437
+ attention_mask = None
438
+
439
+ negative_prompt_embeds = self.text_encoder(
440
+ uncond_input.input_ids.to(device),
441
+ attention_mask=attention_mask,
442
+ )
443
+ negative_prompt_embeds = negative_prompt_embeds[0]
444
+
445
+ if do_classifier_free_guidance:
446
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
447
+ seq_len = negative_prompt_embeds.shape[1]
448
+
449
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
450
+
451
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
452
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
453
+
454
+ if self.text_encoder is not None:
455
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
456
+ # Retrieve the original scale by scaling back the LoRA layers
457
+ unscale_lora_layers(self.text_encoder, lora_scale)
458
+
459
+ return prompt_embeds, negative_prompt_embeds
460
+
461
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
462
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
463
+ dtype = next(self.image_encoder.parameters()).dtype
464
+
465
+ if not isinstance(image, torch.Tensor):
466
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
467
+
468
+ image = image.to(device=device, dtype=dtype)
469
+ if output_hidden_states:
470
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
471
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
472
+ uncond_image_enc_hidden_states = self.image_encoder(
473
+ torch.zeros_like(image), output_hidden_states=True
474
+ ).hidden_states[-2]
475
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
476
+ num_images_per_prompt, dim=0
477
+ )
478
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
479
+ else:
480
+ image_embeds = self.image_encoder(image).image_embeds
481
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
482
+ uncond_image_embeds = torch.zeros_like(image_embeds)
483
+
484
+ return image_embeds, uncond_image_embeds
485
+
486
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
487
+ def prepare_ip_adapter_image_embeds(
488
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
489
+ ):
490
+ image_embeds = []
491
+ if do_classifier_free_guidance:
492
+ negative_image_embeds = []
493
+ if ip_adapter_image_embeds is None:
494
+ if not isinstance(ip_adapter_image, list):
495
+ ip_adapter_image = [ip_adapter_image]
496
+
497
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
498
+ raise ValueError(
499
+ 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."
500
+ )
501
+
502
+ for single_ip_adapter_image, image_proj_layer in zip(
503
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
504
+ ):
505
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
506
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
507
+ single_ip_adapter_image, device, 1, output_hidden_state
508
+ )
509
+
510
+ image_embeds.append(single_image_embeds[None, :])
511
+ if do_classifier_free_guidance:
512
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
513
+ else:
514
+ for single_image_embeds in ip_adapter_image_embeds:
515
+ if do_classifier_free_guidance:
516
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
517
+ negative_image_embeds.append(single_negative_image_embeds)
518
+ image_embeds.append(single_image_embeds)
519
+
520
+ ip_adapter_image_embeds = []
521
+ for i, single_image_embeds in enumerate(image_embeds):
522
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
523
+ if do_classifier_free_guidance:
524
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
525
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
526
+
527
+ single_image_embeds = single_image_embeds.to(device=device)
528
+ ip_adapter_image_embeds.append(single_image_embeds)
529
+
530
+ return ip_adapter_image_embeds
531
+
532
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
533
+ def run_safety_checker(self, image, device, dtype):
534
+ if self.safety_checker is None:
535
+ has_nsfw_concept = None
536
+ else:
537
+ if torch.is_tensor(image):
538
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
539
+ else:
540
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
541
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
542
+ image, has_nsfw_concept = self.safety_checker(
543
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
544
+ )
545
+ return image, has_nsfw_concept
546
+
547
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
548
+ def prepare_extra_step_kwargs(self, generator, eta):
549
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
550
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
551
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
552
+ # and should be between [0, 1]
553
+
554
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
555
+ extra_step_kwargs = {}
556
+ if accepts_eta:
557
+ extra_step_kwargs["eta"] = eta
558
+
559
+ # check if the scheduler accepts generator
560
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
561
+ if accepts_generator:
562
+ extra_step_kwargs["generator"] = generator
563
+ return extra_step_kwargs
564
+
565
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
566
+ def check_inputs(
567
+ self,
568
+ prompt,
569
+ height,
570
+ width,
571
+ callback_steps,
572
+ negative_prompt=None,
573
+ prompt_embeds=None,
574
+ negative_prompt_embeds=None,
575
+ ip_adapter_image=None,
576
+ ip_adapter_image_embeds=None,
577
+ callback_on_step_end_tensor_inputs=None,
578
+ ):
579
+ if height % 8 != 0 or width % 8 != 0:
580
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
581
+
582
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
583
+ raise ValueError(
584
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
585
+ f" {type(callback_steps)}."
586
+ )
587
+ if callback_on_step_end_tensor_inputs is not None and not all(
588
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
589
+ ):
590
+ raise ValueError(
591
+ 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]}"
592
+ )
593
+
594
+ if prompt is not None and prompt_embeds is not None:
595
+ raise ValueError(
596
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
597
+ " only forward one of the two."
598
+ )
599
+ elif prompt is None and prompt_embeds is None:
600
+ raise ValueError(
601
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
602
+ )
603
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
604
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
605
+
606
+ if negative_prompt is not None and negative_prompt_embeds is not None:
607
+ raise ValueError(
608
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
609
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
610
+ )
611
+
612
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
613
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
614
+ raise ValueError(
615
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
616
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
617
+ f" {negative_prompt_embeds.shape}."
618
+ )
619
+
620
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
621
+ raise ValueError(
622
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
623
+ )
624
+
625
+ if ip_adapter_image_embeds is not None:
626
+ if not isinstance(ip_adapter_image_embeds, list):
627
+ raise ValueError(
628
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
629
+ )
630
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
631
+ raise ValueError(
632
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
633
+ )
634
+
635
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
636
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
637
+ shape = (
638
+ batch_size,
639
+ num_channels_latents,
640
+ int(height) // self.vae_scale_factor,
641
+ int(width) // self.vae_scale_factor,
642
+ )
643
+ if isinstance(generator, list) and len(generator) != batch_size:
644
+ raise ValueError(
645
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
646
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
647
+ )
648
+
649
+ if latents is None:
650
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
651
+ else:
652
+ latents = latents.to(device)
653
+
654
+ # scale the initial noise by the standard deviation required by the scheduler
655
+ latents = latents * self.scheduler.init_noise_sigma
656
+ return latents
657
+
658
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
659
+ def get_guidance_scale_embedding(
660
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
661
+ ) -> torch.Tensor:
662
+ """
663
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
664
+
665
+ Args:
666
+ w (`torch.Tensor`):
667
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
668
+ embedding_dim (`int`, *optional*, defaults to 512):
669
+ Dimension of the embeddings to generate.
670
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
671
+ Data type of the generated embeddings.
672
+
673
+ Returns:
674
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
675
+ """
676
+ assert len(w.shape) == 1
677
+ w = w * 1000.0
678
+
679
+ half_dim = embedding_dim // 2
680
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
681
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
682
+ emb = w.to(dtype)[:, None] * emb[None, :]
683
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
684
+ if embedding_dim % 2 == 1: # zero pad
685
+ emb = torch.nn.functional.pad(emb, (0, 1))
686
+ assert emb.shape == (w.shape[0], embedding_dim)
687
+ return emb
688
+
689
+ @property
690
+ def guidance_scale(self):
691
+ return self._guidance_scale
692
+
693
+ @property
694
+ def guidance_rescale(self):
695
+ return self._guidance_rescale
696
+
697
+ @property
698
+ def clip_skip(self):
699
+ return self._clip_skip
700
+
701
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
702
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
703
+ # corresponds to doing no classifier free guidance.
704
+ @property
705
+ def do_classifier_free_guidance(self):
706
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
707
+
708
+ @property
709
+ def cross_attention_kwargs(self):
710
+ return self._cross_attention_kwargs
711
+
712
+ @property
713
+ def num_timesteps(self):
714
+ return self._num_timesteps
715
+
716
+ @property
717
+ def interrupt(self):
718
+ return self._interrupt
719
+
720
+ @torch.no_grad()
721
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
722
+ def __call__(
723
+ self,
724
+ prompt: Union[str, List[str]] = None,
725
+ height: Optional[int] = None,
726
+ width: Optional[int] = None,
727
+ num_inference_steps: int = 50,
728
+ timesteps: List[int] = None,
729
+ sigmas: List[float] = None,
730
+ guidance_scale: float = 7.5,
731
+ negative_prompt: Optional[Union[str, List[str]]] = None,
732
+ num_images_per_prompt: Optional[int] = 1,
733
+ eta: float = 0.0,
734
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
735
+ latents: Optional[torch.Tensor] = None,
736
+ prompt_embeds: Optional[torch.Tensor] = None,
737
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
738
+ ip_adapter_image: Optional[PipelineImageInput] = None,
739
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
740
+ output_type: Optional[str] = "pil",
741
+ return_dict: bool = True,
742
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
743
+ guidance_rescale: float = 0.0,
744
+ clip_skip: Optional[int] = None,
745
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
746
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
747
+ pag_scale: float = 3.0,
748
+ pag_adaptive_scale: float = 0.0,
749
+ ):
750
+ r"""
751
+ The call function to the pipeline for generation.
752
+
753
+ Args:
754
+ prompt (`str` or `List[str]`, *optional*):
755
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
756
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
757
+ The height in pixels of the generated image.
758
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
759
+ The width in pixels of the generated image.
760
+ num_inference_steps (`int`, *optional*, defaults to 50):
761
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
762
+ expense of slower inference.
763
+ timesteps (`List[int]`, *optional*):
764
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
765
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
766
+ passed will be used. Must be in descending order.
767
+ sigmas (`List[float]`, *optional*):
768
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
769
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
770
+ will be used.
771
+ guidance_scale (`float`, *optional*, defaults to 7.5):
772
+ A higher guidance scale value encourages the model to generate images closely linked to the text
773
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
774
+ negative_prompt (`str` or `List[str]`, *optional*):
775
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
776
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
777
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
778
+ The number of images to generate per prompt.
779
+ eta (`float`, *optional*, defaults to 0.0):
780
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
781
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
782
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
783
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
784
+ generation deterministic.
785
+ latents (`torch.Tensor`, *optional*):
786
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
787
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
788
+ tensor is generated by sampling using the supplied random `generator`.
789
+ prompt_embeds (`torch.Tensor`, *optional*):
790
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
791
+ provided, text embeddings are generated from the `prompt` input argument.
792
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
793
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
794
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
795
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
796
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
797
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
798
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
799
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
800
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
801
+ output_type (`str`, *optional*, defaults to `"pil"`):
802
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
803
+ return_dict (`bool`, *optional*, defaults to `True`):
804
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
805
+ plain tuple.
806
+ cross_attention_kwargs (`dict`, *optional*):
807
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
808
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
809
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
810
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
811
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
812
+ using zero terminal SNR.
813
+ clip_skip (`int`, *optional*):
814
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
815
+ the output of the pre-final layer will be used for computing the prompt embeddings.
816
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
817
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
818
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
819
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
820
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
821
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
822
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
823
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
824
+ `._callback_tensor_inputs` attribute of your pipeline class.
825
+ pag_scale (`float`, *optional*, defaults to 3.0):
826
+ The scale factor for the perturbed attention guidance. If it is set to 0.0, the perturbed attention
827
+ guidance will not be used.
828
+ pag_adaptive_scale (`float`, *optional*, defaults to 0.0):
829
+ The adaptive scale factor for the perturbed attention guidance. If it is set to 0.0, `pag_scale` is
830
+ used.
831
+
832
+ Examples:
833
+
834
+ Returns:
835
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
836
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
837
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
838
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
839
+ "not-safe-for-work" (nsfw) content.
840
+ """
841
+
842
+ # 0. Default height and width to unet
843
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
844
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
845
+ # to deal with lora scaling and other possible forward hooks
846
+
847
+ # 1. Check inputs. Raise error if not correct
848
+ self.check_inputs(
849
+ prompt,
850
+ height,
851
+ width,
852
+ None,
853
+ negative_prompt,
854
+ prompt_embeds,
855
+ negative_prompt_embeds,
856
+ ip_adapter_image,
857
+ ip_adapter_image_embeds,
858
+ callback_on_step_end_tensor_inputs,
859
+ )
860
+
861
+ self._guidance_scale = guidance_scale
862
+ self._guidance_rescale = guidance_rescale
863
+ self._clip_skip = clip_skip
864
+ self._cross_attention_kwargs = cross_attention_kwargs
865
+ self._interrupt = False
866
+ self._pag_scale = pag_scale
867
+ self._pag_adaptive_scale = pag_adaptive_scale
868
+
869
+ # 2. Define call parameters
870
+ if prompt is not None and isinstance(prompt, str):
871
+ batch_size = 1
872
+ elif prompt is not None and isinstance(prompt, list):
873
+ batch_size = len(prompt)
874
+ else:
875
+ batch_size = prompt_embeds.shape[0]
876
+
877
+ device = self._execution_device
878
+
879
+ # 3. Encode input prompt
880
+ lora_scale = (
881
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
882
+ )
883
+
884
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
885
+ prompt,
886
+ device,
887
+ num_images_per_prompt,
888
+ self.do_classifier_free_guidance,
889
+ negative_prompt,
890
+ prompt_embeds=prompt_embeds,
891
+ negative_prompt_embeds=negative_prompt_embeds,
892
+ lora_scale=lora_scale,
893
+ clip_skip=self.clip_skip,
894
+ )
895
+
896
+ # For classifier free guidance, we need to do two forward passes.
897
+ # Here we concatenate the unconditional and text embeddings into a single batch
898
+ # to avoid doing two forward passes
899
+ if self.do_perturbed_attention_guidance:
900
+ prompt_embeds = self._prepare_perturbed_attention_guidance(
901
+ prompt_embeds, negative_prompt_embeds, self.do_classifier_free_guidance
902
+ )
903
+ elif self.do_classifier_free_guidance:
904
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
905
+
906
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
907
+ ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
908
+ ip_adapter_image,
909
+ ip_adapter_image_embeds,
910
+ device,
911
+ batch_size * num_images_per_prompt,
912
+ self.do_classifier_free_guidance,
913
+ )
914
+
915
+ for i, image_embeds in enumerate(ip_adapter_image_embeds):
916
+ negative_image_embeds = None
917
+ if self.do_classifier_free_guidance:
918
+ negative_image_embeds, image_embeds = image_embeds.chunk(2)
919
+ if self.do_perturbed_attention_guidance:
920
+ image_embeds = self._prepare_perturbed_attention_guidance(
921
+ image_embeds, negative_image_embeds, self.do_classifier_free_guidance
922
+ )
923
+
924
+ elif self.do_classifier_free_guidance:
925
+ image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0)
926
+ image_embeds = image_embeds.to(device)
927
+ ip_adapter_image_embeds[i] = image_embeds
928
+
929
+ # 4. Prepare timesteps
930
+ timesteps, num_inference_steps = retrieve_timesteps(
931
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
932
+ )
933
+
934
+ # 5. Prepare latent variables
935
+ num_channels_latents = self.unet.config.in_channels
936
+ latents = self.prepare_latents(
937
+ batch_size * num_images_per_prompt,
938
+ num_channels_latents,
939
+ height,
940
+ width,
941
+ prompt_embeds.dtype,
942
+ device,
943
+ generator,
944
+ latents,
945
+ )
946
+
947
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
948
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
949
+
950
+ # 6.1 Add image embeds for IP-Adapter
951
+ added_cond_kwargs = (
952
+ {"image_embeds": ip_adapter_image_embeds}
953
+ if (ip_adapter_image is not None or ip_adapter_image_embeds is not None)
954
+ else None
955
+ )
956
+
957
+ # 6.2 Optionally get Guidance Scale Embedding
958
+ timestep_cond = None
959
+ if self.unet.config.time_cond_proj_dim is not None:
960
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
961
+ timestep_cond = self.get_guidance_scale_embedding(
962
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
963
+ ).to(device=device, dtype=latents.dtype)
964
+
965
+ # 7. Denoising loop
966
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
967
+ if self.do_perturbed_attention_guidance:
968
+ original_attn_proc = self.unet.attn_processors
969
+ self._set_pag_attn_processor(
970
+ pag_applied_layers=self.pag_applied_layers,
971
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
972
+ )
973
+ self._num_timesteps = len(timesteps)
974
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
975
+ for i, t in enumerate(timesteps):
976
+ if self.interrupt:
977
+ continue
978
+
979
+ # expand the latents if we are doing classifier free guidance
980
+ latent_model_input = torch.cat([latents] * (prompt_embeds.shape[0] // latents.shape[0]))
981
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
982
+
983
+ # predict the noise residual
984
+ noise_pred = self.unet(
985
+ latent_model_input,
986
+ t,
987
+ encoder_hidden_states=prompt_embeds,
988
+ timestep_cond=timestep_cond,
989
+ cross_attention_kwargs=self.cross_attention_kwargs,
990
+ added_cond_kwargs=added_cond_kwargs,
991
+ return_dict=False,
992
+ )[0]
993
+
994
+ # perform guidance
995
+ if self.do_perturbed_attention_guidance:
996
+ noise_pred = self._apply_perturbed_attention_guidance(
997
+ noise_pred, self.do_classifier_free_guidance, self.guidance_scale, t
998
+ )
999
+
1000
+ elif self.do_classifier_free_guidance:
1001
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1002
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1003
+
1004
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1005
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1006
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1007
+
1008
+ # compute the previous noisy sample x_t -> x_t-1
1009
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1010
+
1011
+ if callback_on_step_end is not None:
1012
+ callback_kwargs = {}
1013
+ for k in callback_on_step_end_tensor_inputs:
1014
+ callback_kwargs[k] = locals()[k]
1015
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1016
+
1017
+ latents = callback_outputs.pop("latents", latents)
1018
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1019
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1020
+
1021
+ # call the callback, if provided
1022
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1023
+ progress_bar.update()
1024
+
1025
+ if not output_type == "latent":
1026
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1027
+ 0
1028
+ ]
1029
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1030
+ else:
1031
+ image = latents
1032
+ has_nsfw_concept = None
1033
+
1034
+ if has_nsfw_concept is None:
1035
+ do_denormalize = [True] * image.shape[0]
1036
+ else:
1037
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1038
+
1039
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1040
+
1041
+ # Offload all models
1042
+ self.maybe_free_model_hooks()
1043
+
1044
+ if self.do_perturbed_attention_guidance:
1045
+ self.unet.set_attn_processor(original_attn_proc)
1046
+
1047
+ if not return_dict:
1048
+ return (image, has_nsfw_concept)
1049
+
1050
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)