rynmurdock commited on
Commit
23975d5
1 Parent(s): 985911b

Upload patch_sdxl.py

Browse files
Files changed (1) hide show
  1. patch_sdxl.py +585 -0
patch_sdxl.py ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+ import inspect
5
+ from typing import Any, Callable, Dict, List, Optional, Union, Tuple
6
+
7
+ from diffusers import StableDiffusionXLPipeline
8
+
9
+ import torch
10
+ from packaging import version
11
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
12
+
13
+ from diffusers.configuration_utils import FrozenDict
14
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
15
+ from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
16
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
17
+ from diffusers.models.attention_processor import FusedAttnProcessor2_0
18
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
19
+ from diffusers.schedulers import KarrasDiffusionSchedulers
20
+ from diffusers.utils import (
21
+ USE_PEFT_BACKEND,
22
+ deprecate,
23
+ logging,
24
+ replace_example_docstring,
25
+ scale_lora_layers,
26
+ unscale_lora_layers,
27
+ )
28
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
29
+
30
+
31
+
32
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
33
+ from transformers import CLIPFeatureExtractor
34
+ import numpy as np
35
+ import torch
36
+ from PIL import Image
37
+ from typing import Optional, Tuple, Union
38
+
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+ torch_device = device
41
+ torch_dtype = torch.float16
42
+
43
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(
44
+ "CompVis/stable-diffusion-safety-checker"
45
+ ).to(device)
46
+ feature_extractor = CLIPFeatureExtractor.from_pretrained(
47
+ "openai/clip-vit-base-patch32"
48
+ )
49
+
50
+ def check_nsfw_images(
51
+ images: list[Image.Image],
52
+ ) -> list[bool]:
53
+ safety_checker_input = feature_extractor(images, return_tensors="pt").to(device)
54
+ images_np = [np.array(img) for img in images]
55
+
56
+ _, has_nsfw_concepts = safety_checker(
57
+ images=images_np,
58
+ clip_input=safety_checker_input.pixel_values.to(torch_device),
59
+ )
60
+ return has_nsfw_concepts
61
+
62
+
63
+
64
+
65
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
66
+
67
+ EXAMPLE_DOC_STRING = """
68
+ Examples:
69
+ ```py
70
+ >>> import torch
71
+ >>> from diffusers import StableDiffusionPipeline
72
+
73
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
74
+ >>> pipe = pipe.to("cuda")
75
+
76
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
77
+ >>> image = pipe(prompt).images[0]
78
+ ```
79
+ """
80
+
81
+
82
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
83
+ """
84
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
85
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
86
+ """
87
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
88
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
89
+ # rescale the results from guidance (fixes overexposure)
90
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
91
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
92
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
93
+ return noise_cfg
94
+
95
+
96
+ def retrieve_timesteps(
97
+ scheduler,
98
+ num_inference_steps: Optional[int] = None,
99
+ device: Optional[Union[str, torch.device]] = None,
100
+ timesteps: Optional[List[int]] = None,
101
+ **kwargs,
102
+ ):
103
+ """
104
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
105
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
106
+
107
+ Args:
108
+ scheduler (`SchedulerMixin`):
109
+ The scheduler to get timesteps from.
110
+ num_inference_steps (`int`):
111
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
112
+ `timesteps` must be `None`.
113
+ device (`str` or `torch.device`, *optional*):
114
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
115
+ timesteps (`List[int]`, *optional*):
116
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
117
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
118
+ must be `None`.
119
+
120
+ Returns:
121
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
122
+ second element is the number of inference steps.
123
+ """
124
+ if timesteps is not None:
125
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
126
+ if not accepts_timesteps:
127
+ raise ValueError(
128
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
129
+ f" timestep schedules. Please check whether you are using the correct scheduler."
130
+ )
131
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
132
+ timesteps = scheduler.timesteps
133
+ num_inference_steps = len(timesteps)
134
+ else:
135
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
136
+ timesteps = scheduler.timesteps
137
+ return timesteps, num_inference_steps
138
+
139
+
140
+ class SDEmb(StableDiffusionXLPipeline):
141
+ @torch.no_grad()
142
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
143
+ def __call__(
144
+ self,
145
+ prompt: Union[str, List[str]] = None,
146
+ prompt_2: Optional[Union[str, List[str]]] = None,
147
+ height: Optional[int] = None,
148
+ width: Optional[int] = None,
149
+ num_inference_steps: int = 50,
150
+ timesteps: List[int] = None,
151
+ denoising_end: Optional[float] = None,
152
+ guidance_scale: float = 5.0,
153
+ negative_prompt: Optional[Union[str, List[str]]] = None,
154
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
155
+ num_images_per_prompt: Optional[int] = 1,
156
+ eta: float = 0.0,
157
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
158
+ latents: Optional[torch.FloatTensor] = None,
159
+ prompt_embeds: Optional[torch.FloatTensor] = None,
160
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
161
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
162
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
163
+ ip_adapter_image: Optional[PipelineImageInput] = None,
164
+ output_type: Optional[str] = "pil",
165
+ return_dict: bool = True,
166
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
167
+ guidance_rescale: float = 0.0,
168
+ original_size: Optional[Tuple[int, int]] = None,
169
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
170
+ target_size: Optional[Tuple[int, int]] = None,
171
+ negative_original_size: Optional[Tuple[int, int]] = None,
172
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
173
+ negative_target_size: Optional[Tuple[int, int]] = None,
174
+ clip_skip: Optional[int] = None,
175
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
176
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
177
+ ip_adapter_emb=None,
178
+ **kwargs,
179
+ ):
180
+ r"""
181
+ Function invoked when calling the pipeline for generation.
182
+
183
+ Args:
184
+ prompt (`str` or `List[str]`, *optional*):
185
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
186
+ instead.
187
+ prompt_2 (`str` or `List[str]`, *optional*):
188
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
189
+ used in both text-encoders
190
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
191
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
192
+ Anything below 512 pixels won't work well for
193
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
194
+ and checkpoints that are not specifically fine-tuned on low resolutions.
195
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
196
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
197
+ Anything below 512 pixels won't work well for
198
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
199
+ and checkpoints that are not specifically fine-tuned on low resolutions.
200
+ num_inference_steps (`int`, *optional*, defaults to 50):
201
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
202
+ expense of slower inference.
203
+ timesteps (`List[int]`, *optional*):
204
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
205
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
206
+ passed will be used. Must be in descending order.
207
+ denoising_end (`float`, *optional*):
208
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
209
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
210
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
211
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
212
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
213
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
214
+ guidance_scale (`float`, *optional*, defaults to 5.0):
215
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
216
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
217
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
218
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
219
+ usually at the expense of lower image quality.
220
+ negative_prompt (`str` or `List[str]`, *optional*):
221
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
222
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
223
+ less than `1`).
224
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
225
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
226
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
227
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
228
+ The number of images to generate per prompt.
229
+ eta (`float`, *optional*, defaults to 0.0):
230
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
231
+ [`schedulers.DDIMScheduler`], will be ignored for others.
232
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
233
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
234
+ to make generation deterministic.
235
+ latents (`torch.FloatTensor`, *optional*):
236
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
237
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
238
+ tensor will ge generated by sampling using the supplied random `generator`.
239
+ prompt_embeds (`torch.FloatTensor`, *optional*):
240
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
241
+ provided, text embeddings will be generated from `prompt` input argument.
242
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
243
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
244
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
245
+ argument.
246
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
247
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
248
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
249
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
250
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
251
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
252
+ input argument.
253
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
254
+ output_type (`str`, *optional*, defaults to `"pil"`):
255
+ The output format of the generate image. Choose between
256
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
257
+ return_dict (`bool`, *optional*, defaults to `True`):
258
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
259
+ of a plain tuple.
260
+ cross_attention_kwargs (`dict`, *optional*):
261
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
262
+ `self.processor` in
263
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
264
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
265
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
266
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
267
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
268
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
269
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
270
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
271
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
272
+ explained in section 2.2 of
273
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
274
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
275
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
276
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
277
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
278
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
279
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
280
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
281
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
282
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
283
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
284
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
285
+ micro-conditioning as explained in section 2.2 of
286
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
287
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
288
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
289
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
290
+ micro-conditioning as explained in section 2.2 of
291
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
292
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
293
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
294
+ To negatively condition the generation process based on a target image resolution. It should be as same
295
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
296
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
297
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
298
+ callback_on_step_end (`Callable`, *optional*):
299
+ A function that calls at the end of each denoising steps during the inference. The function is called
300
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
301
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
302
+ `callback_on_step_end_tensor_inputs`.
303
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
304
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
305
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
306
+ `._callback_tensor_inputs` attribute of your pipeline class.
307
+
308
+ Examples:
309
+
310
+ Returns:
311
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
312
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
313
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
314
+ """
315
+
316
+ callback = kwargs.pop("callback", None)
317
+ callback_steps = kwargs.pop("callback_steps", None)
318
+
319
+ if callback is not None:
320
+ deprecate(
321
+ "callback",
322
+ "1.0.0",
323
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
324
+ )
325
+ if callback_steps is not None:
326
+ deprecate(
327
+ "callback_steps",
328
+ "1.0.0",
329
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
330
+ )
331
+
332
+ # 0. Default height and width to unet
333
+ height = height or self.default_sample_size * self.vae_scale_factor
334
+ width = width or self.default_sample_size * self.vae_scale_factor
335
+
336
+ original_size = original_size or (height, width)
337
+ target_size = target_size or (height, width)
338
+
339
+ # 1. Check inputs. Raise error if not correct
340
+ self.check_inputs(
341
+ prompt,
342
+ prompt_2,
343
+ height,
344
+ width,
345
+ callback_steps,
346
+ negative_prompt,
347
+ negative_prompt_2,
348
+ prompt_embeds,
349
+ negative_prompt_embeds,
350
+ pooled_prompt_embeds,
351
+ negative_pooled_prompt_embeds,
352
+ callback_on_step_end_tensor_inputs,
353
+ )
354
+
355
+ self._guidance_scale = guidance_scale
356
+ self._guidance_rescale = guidance_rescale
357
+ self._clip_skip = clip_skip
358
+ self._cross_attention_kwargs = cross_attention_kwargs
359
+ self._denoising_end = denoising_end
360
+ self._interrupt = False
361
+
362
+ # 2. Define call parameters
363
+ if prompt is not None and isinstance(prompt, str):
364
+ batch_size = 1
365
+ elif prompt is not None and isinstance(prompt, list):
366
+ batch_size = len(prompt)
367
+ else:
368
+ batch_size = prompt_embeds.shape[0]
369
+
370
+ device = self._execution_device
371
+
372
+ # 3. Encode input prompt
373
+ lora_scale = (
374
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
375
+ )
376
+
377
+ (
378
+ prompt_embeds,
379
+ negative_prompt_embeds,
380
+ pooled_prompt_embeds,
381
+ negative_pooled_prompt_embeds,
382
+ ) = self.encode_prompt(
383
+ prompt=prompt,
384
+ prompt_2=prompt_2,
385
+ device=device,
386
+ num_images_per_prompt=num_images_per_prompt,
387
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
388
+ negative_prompt=negative_prompt,
389
+ negative_prompt_2=negative_prompt_2,
390
+ prompt_embeds=prompt_embeds,
391
+ negative_prompt_embeds=negative_prompt_embeds,
392
+ pooled_prompt_embeds=pooled_prompt_embeds,
393
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
394
+ lora_scale=lora_scale,
395
+ clip_skip=self.clip_skip,
396
+ )
397
+
398
+ # 4. Prepare timesteps
399
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
400
+
401
+ # 5. Prepare latent variables
402
+ num_channels_latents = self.unet.config.in_channels
403
+ latents = self.prepare_latents(
404
+ batch_size * num_images_per_prompt,
405
+ num_channels_latents,
406
+ height,
407
+ width,
408
+ prompt_embeds.dtype,
409
+ device,
410
+ generator,
411
+ latents,
412
+ )
413
+
414
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
415
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
416
+
417
+ # 7. Prepare added time ids & embeddings
418
+ add_text_embeds = pooled_prompt_embeds
419
+ if self.text_encoder_2 is None:
420
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
421
+ else:
422
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
423
+
424
+ add_time_ids = self._get_add_time_ids(
425
+ original_size,
426
+ crops_coords_top_left,
427
+ target_size,
428
+ dtype=prompt_embeds.dtype,
429
+ text_encoder_projection_dim=text_encoder_projection_dim,
430
+ )
431
+ if negative_original_size is not None and negative_target_size is not None:
432
+ negative_add_time_ids = self._get_add_time_ids(
433
+ negative_original_size,
434
+ negative_crops_coords_top_left,
435
+ negative_target_size,
436
+ dtype=prompt_embeds.dtype,
437
+ text_encoder_projection_dim=text_encoder_projection_dim,
438
+ )
439
+ else:
440
+ negative_add_time_ids = add_time_ids
441
+
442
+ if self.do_classifier_free_guidance:
443
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
444
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
445
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
446
+
447
+ prompt_embeds = prompt_embeds.to(device)
448
+ add_text_embeds = add_text_embeds.to(device)
449
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
450
+
451
+ if ip_adapter_emb is not None:
452
+ image_embeds = ip_adapter_emb
453
+
454
+ elif ip_adapter_image is not None:
455
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
456
+ image_embeds, negative_image_embeds = self.encode_image(
457
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
458
+ )
459
+ if self.do_classifier_free_guidance:
460
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
461
+
462
+ # 8. Denoising loop
463
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
464
+
465
+ # 8.1 Apply denoising_end
466
+ if (
467
+ self.denoising_end is not None
468
+ and isinstance(self.denoising_end, float)
469
+ and self.denoising_end > 0
470
+ and self.denoising_end < 1
471
+ ):
472
+ discrete_timestep_cutoff = int(
473
+ round(
474
+ self.scheduler.config.num_train_timesteps
475
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
476
+ )
477
+ )
478
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
479
+ timesteps = timesteps[:num_inference_steps]
480
+
481
+ # 9. Optionally get Guidance Scale Embedding
482
+ timestep_cond = None
483
+ if self.unet.config.time_cond_proj_dim is not None:
484
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
485
+ timestep_cond = self.get_guidance_scale_embedding(
486
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
487
+ ).to(device=device, dtype=latents.dtype)
488
+
489
+ self._num_timesteps = len(timesteps)
490
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
491
+ for i, t in enumerate(timesteps):
492
+ if self.interrupt:
493
+ continue
494
+
495
+ # expand the latents if we are doing classifier free guidance
496
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
497
+
498
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
499
+
500
+ # predict the noise residual
501
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
502
+ if ip_adapter_image is not None or ip_adapter_emb is not None:
503
+ added_cond_kwargs["image_embeds"] = image_embeds
504
+ noise_pred = self.unet(
505
+ latent_model_input,
506
+ t,
507
+ encoder_hidden_states=prompt_embeds,
508
+ timestep_cond=timestep_cond,
509
+ cross_attention_kwargs=self.cross_attention_kwargs,
510
+ added_cond_kwargs=added_cond_kwargs,
511
+ return_dict=False,
512
+ )[0]
513
+
514
+ # perform guidance
515
+ if self.do_classifier_free_guidance:
516
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
517
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
518
+
519
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
520
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
521
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
522
+
523
+ # compute the previous noisy sample x_t -> x_t-1
524
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
525
+
526
+ if callback_on_step_end is not None:
527
+ callback_kwargs = {}
528
+ for k in callback_on_step_end_tensor_inputs:
529
+ callback_kwargs[k] = locals()[k]
530
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
531
+
532
+ latents = callback_outputs.pop("latents", latents)
533
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
534
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
535
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
536
+ negative_pooled_prompt_embeds = callback_outputs.pop(
537
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
538
+ )
539
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
540
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
541
+
542
+ # call the callback, if provided
543
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
544
+ progress_bar.update()
545
+ if callback is not None and i % callback_steps == 0:
546
+ step_idx = i // getattr(self.scheduler, "order", 1)
547
+ callback(step_idx, t, latents)
548
+
549
+ # if XLA_AVAILABLE:
550
+ # xm.mark_step()
551
+
552
+ if not output_type == "latent":
553
+ # make sure the VAE is in float32 mode, as it overflows in float16
554
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
555
+
556
+ if needs_upcasting:
557
+ self.upcast_vae()
558
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
559
+
560
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
561
+
562
+ # cast back to fp16 if needed
563
+ if needs_upcasting:
564
+ self.vae.to(dtype=torch.float16)
565
+ else:
566
+ image = latents
567
+
568
+ if not output_type == "latent":
569
+ # apply watermark if available
570
+ if self.watermark is not None:
571
+ image = self.watermark.apply_watermark(image)
572
+
573
+ image = self.image_processor.postprocess(image, output_type=output_type)
574
+ maybe_nsfw = any(check_nsfw_images(image))
575
+ if maybe_nsfw:
576
+ print('This image could be NSFW so we return a blank image.')
577
+ return StableDiffusionXLPipelineOutput(images=[Image.new('RGB', (1024, 1024))])
578
+
579
+ # Offload all models
580
+ self.maybe_free_model_hooks()
581
+
582
+ if not return_dict:
583
+ return (image,)
584
+
585
+ return StableDiffusionXLPipelineOutput(images=image)