sunovivid commited on
Commit
430f06e
1 Parent(s): 7594ae3

Upload pipeline_stable_diffusion_pag.py

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