rynmurdock commited on
Commit
409d236
1 Parent(s): 2738f3b

from diffuses; patch call

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