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