AlanB commited on
Commit
9a33d55
1 Parent(s): ed4614f

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +1467 -0
pipeline.py ADDED
@@ -0,0 +1,1467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ import torchvision
22
+ from transformers import (
23
+ CLIPImageProcessor,
24
+ CLIPTextModel,
25
+ CLIPTextModelWithProjection,
26
+ CLIPTokenizer,
27
+ CLIPVisionModelWithProjection,
28
+ )
29
+
30
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
31
+ from diffusers.loaders import (
32
+ FromSingleFileMixin,
33
+ IPAdapterMixin,
34
+ StableDiffusionXLLoraLoaderMixin,
35
+ TextualInversionLoaderMixin,
36
+ )
37
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
38
+ from diffusers.models.attention_processor import (
39
+ AttnProcessor2_0,
40
+ XFormersAttnProcessor,
41
+ )
42
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
43
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
44
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
45
+ from diffusers.schedulers import KarrasDiffusionSchedulers
46
+ from diffusers.utils import (
47
+ USE_PEFT_BACKEND,
48
+ deprecate,
49
+ is_invisible_watermark_available,
50
+ is_torch_xla_available,
51
+ logging,
52
+ replace_example_docstring,
53
+ scale_lora_layers,
54
+ unscale_lora_layers,
55
+ )
56
+ from diffusers.utils.torch_utils import randn_tensor
57
+
58
+
59
+ if is_invisible_watermark_available():
60
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
61
+
62
+ if is_torch_xla_available():
63
+ import torch_xla.core.xla_model as xm
64
+
65
+ XLA_AVAILABLE = True
66
+ else:
67
+ XLA_AVAILABLE = False
68
+
69
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
70
+
71
+ EXAMPLE_DOC_STRING = """
72
+ Examples:
73
+ ```py
74
+ >>> import torch
75
+ >>> from diffusers import StableDiffusionXLImg2ImgPipeline
76
+ >>> from diffusers.utils import load_image
77
+
78
+ >>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
79
+ ... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
80
+ ... )
81
+ >>> pipe = pipe.to("cuda")
82
+ >>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
83
+
84
+ >>> init_image = load_image(url).convert("RGB")
85
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
86
+ >>> image = pipe(prompt, image=init_image).images[0]
87
+ ```
88
+ """
89
+
90
+
91
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
92
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
93
+ """
94
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
95
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
96
+ """
97
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
98
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
99
+ # rescale the results from guidance (fixes overexposure)
100
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
101
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
102
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
103
+ return noise_cfg
104
+
105
+
106
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
107
+ def retrieve_latents(
108
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
109
+ ):
110
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
111
+ return encoder_output.latent_dist.sample(generator)
112
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
113
+ return encoder_output.latent_dist.mode()
114
+ elif hasattr(encoder_output, "latents"):
115
+ return encoder_output.latents
116
+ else:
117
+ raise AttributeError("Could not access latents of provided encoder_output")
118
+
119
+
120
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
121
+ def retrieve_timesteps(
122
+ scheduler,
123
+ num_inference_steps: Optional[int] = None,
124
+ device: Optional[Union[str, torch.device]] = None,
125
+ timesteps: Optional[List[int]] = None,
126
+ **kwargs,
127
+ ):
128
+ """
129
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
130
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
131
+
132
+ Args:
133
+ scheduler (`SchedulerMixin`):
134
+ The scheduler to get timesteps from.
135
+ num_inference_steps (`int`):
136
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
137
+ `timesteps` must be `None`.
138
+ device (`str` or `torch.device`, *optional*):
139
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
140
+ timesteps (`List[int]`, *optional*):
141
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
142
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
143
+ must be `None`.
144
+
145
+ Returns:
146
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
147
+ second element is the number of inference steps.
148
+ """
149
+ if timesteps is not None:
150
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
151
+ if not accepts_timesteps:
152
+ raise ValueError(
153
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
154
+ f" timestep schedules. Please check whether you are using the correct scheduler."
155
+ )
156
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
157
+ timesteps = scheduler.timesteps
158
+ num_inference_steps = len(timesteps)
159
+ else:
160
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
161
+ timesteps = scheduler.timesteps
162
+ return timesteps, num_inference_steps
163
+
164
+
165
+ class StableDiffusionXLDifferentialImg2ImgPipeline(
166
+ DiffusionPipeline,
167
+ StableDiffusionMixin,
168
+ TextualInversionLoaderMixin,
169
+ FromSingleFileMixin,
170
+ StableDiffusionXLLoraLoaderMixin,
171
+ IPAdapterMixin,
172
+ ):
173
+ r"""
174
+ Pipeline for text-to-image generation using Stable Diffusion XL.
175
+
176
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
177
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
178
+
179
+ In addition the pipeline inherits the following loading methods:
180
+ - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]
181
+ - *LoRA*: [`loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`]
182
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
183
+
184
+ as well as the following saving methods:
185
+ - *LoRA*: [`loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`]
186
+
187
+ Args:
188
+ vae ([`AutoencoderKL`]):
189
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
190
+ text_encoder ([`CLIPTextModel`]):
191
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
192
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
193
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
194
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
195
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
196
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
197
+ specifically the
198
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
199
+ variant.
200
+ tokenizer (`CLIPTokenizer`):
201
+ Tokenizer of class
202
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
203
+ tokenizer_2 (`CLIPTokenizer`):
204
+ Second Tokenizer of class
205
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
206
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
207
+ scheduler ([`SchedulerMixin`]):
208
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
209
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
210
+ """
211
+
212
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
213
+ _optional_components = [
214
+ "tokenizer",
215
+ "tokenizer_2",
216
+ "text_encoder",
217
+ "text_encoder_2",
218
+ "image_encoder",
219
+ "feature_extractor",
220
+ ]
221
+ _callback_tensor_inputs = [
222
+ "latents",
223
+ "prompt_embeds",
224
+ "negative_prompt_embeds",
225
+ "add_text_embeds",
226
+ "add_time_ids",
227
+ "negative_pooled_prompt_embeds",
228
+ "add_neg_time_ids",
229
+ ]
230
+
231
+ def __init__(
232
+ self,
233
+ vae: AutoencoderKL,
234
+ text_encoder: CLIPTextModel,
235
+ text_encoder_2: CLIPTextModelWithProjection,
236
+ tokenizer: CLIPTokenizer,
237
+ tokenizer_2: CLIPTokenizer,
238
+ unet: UNet2DConditionModel,
239
+ scheduler: KarrasDiffusionSchedulers,
240
+ image_encoder: CLIPVisionModelWithProjection = None,
241
+ feature_extractor: CLIPImageProcessor = None,
242
+ requires_aesthetics_score: bool = False,
243
+ force_zeros_for_empty_prompt: bool = True,
244
+ add_watermarker: Optional[bool] = None,
245
+ ):
246
+ super().__init__()
247
+
248
+ self.register_modules(
249
+ vae=vae,
250
+ text_encoder=text_encoder,
251
+ text_encoder_2=text_encoder_2,
252
+ tokenizer=tokenizer,
253
+ tokenizer_2=tokenizer_2,
254
+ unet=unet,
255
+ image_encoder=image_encoder,
256
+ feature_extractor=feature_extractor,
257
+ scheduler=scheduler,
258
+ )
259
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
260
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
261
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
262
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
263
+
264
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
265
+
266
+ if add_watermarker:
267
+ self.watermark = StableDiffusionXLWatermarker()
268
+ else:
269
+ self.watermark = None
270
+
271
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
272
+ def encode_prompt(
273
+ self,
274
+ prompt: str,
275
+ prompt_2: Optional[str] = None,
276
+ device: Optional[torch.device] = None,
277
+ num_images_per_prompt: int = 1,
278
+ do_classifier_free_guidance: bool = True,
279
+ negative_prompt: Optional[str] = None,
280
+ negative_prompt_2: Optional[str] = None,
281
+ prompt_embeds: Optional[torch.Tensor] = None,
282
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
283
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
284
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
285
+ lora_scale: Optional[float] = None,
286
+ clip_skip: Optional[int] = None,
287
+ ):
288
+ r"""
289
+ Encodes the prompt into text encoder hidden states.
290
+
291
+ Args:
292
+ prompt (`str` or `List[str]`, *optional*):
293
+ prompt to be encoded
294
+ prompt_2 (`str` or `List[str]`, *optional*):
295
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
296
+ used in both text-encoders
297
+ device: (`torch.device`):
298
+ torch device
299
+ num_images_per_prompt (`int`):
300
+ number of images that should be generated per prompt
301
+ do_classifier_free_guidance (`bool`):
302
+ whether to use classifier free guidance or not
303
+ negative_prompt (`str` or `List[str]`, *optional*):
304
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
305
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
306
+ less than `1`).
307
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
308
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
309
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
310
+ prompt_embeds (`torch.Tensor`, *optional*):
311
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
312
+ provided, text embeddings will be generated from `prompt` input argument.
313
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
314
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
315
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
316
+ argument.
317
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
318
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
319
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
320
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
321
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
322
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
323
+ input argument.
324
+ lora_scale (`float`, *optional*):
325
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
326
+ clip_skip (`int`, *optional*):
327
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
328
+ the output of the pre-final layer will be used for computing the prompt embeddings.
329
+ """
330
+ device = device or self._execution_device
331
+
332
+ # set lora scale so that monkey patched LoRA
333
+ # function of text encoder can correctly access it
334
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
335
+ self._lora_scale = lora_scale
336
+
337
+ # dynamically adjust the LoRA scale
338
+ if self.text_encoder is not None:
339
+ if not USE_PEFT_BACKEND:
340
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
341
+ else:
342
+ scale_lora_layers(self.text_encoder, lora_scale)
343
+
344
+ if self.text_encoder_2 is not None:
345
+ if not USE_PEFT_BACKEND:
346
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
347
+ else:
348
+ scale_lora_layers(self.text_encoder_2, lora_scale)
349
+
350
+ prompt = [prompt] if isinstance(prompt, str) else prompt
351
+
352
+ if prompt is not None:
353
+ batch_size = len(prompt)
354
+ else:
355
+ batch_size = prompt_embeds.shape[0]
356
+
357
+ # Define tokenizers and text encoders
358
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
359
+ text_encoders = (
360
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
361
+ )
362
+
363
+ if prompt_embeds is None:
364
+ prompt_2 = prompt_2 or prompt
365
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
366
+
367
+ # textual inversion: process multi-vector tokens if necessary
368
+ prompt_embeds_list = []
369
+ prompts = [prompt, prompt_2]
370
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
371
+ if isinstance(self, TextualInversionLoaderMixin):
372
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
373
+
374
+ text_inputs = tokenizer(
375
+ prompt,
376
+ padding="max_length",
377
+ max_length=tokenizer.model_max_length,
378
+ truncation=True,
379
+ return_tensors="pt",
380
+ )
381
+
382
+ text_input_ids = text_inputs.input_ids
383
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
384
+
385
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
386
+ text_input_ids, untruncated_ids
387
+ ):
388
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
389
+ logger.warning(
390
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
391
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
392
+ )
393
+
394
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
395
+
396
+ # We are only ALWAYS interested in the pooled output of the final text encoder
397
+ pooled_prompt_embeds = prompt_embeds[0]
398
+ if clip_skip is None:
399
+ prompt_embeds = prompt_embeds.hidden_states[-2]
400
+ else:
401
+ # "2" because SDXL always indexes from the penultimate layer.
402
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
403
+
404
+ prompt_embeds_list.append(prompt_embeds)
405
+
406
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
407
+
408
+ # get unconditional embeddings for classifier free guidance
409
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
410
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
411
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
412
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
413
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
414
+ negative_prompt = negative_prompt or ""
415
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
416
+
417
+ # normalize str to list
418
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
419
+ negative_prompt_2 = (
420
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
421
+ )
422
+
423
+ uncond_tokens: List[str]
424
+ if prompt is not None and type(prompt) is not type(negative_prompt):
425
+ raise TypeError(
426
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
427
+ f" {type(prompt)}."
428
+ )
429
+ elif batch_size != len(negative_prompt):
430
+ raise ValueError(
431
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
432
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
433
+ " the batch size of `prompt`."
434
+ )
435
+ else:
436
+ uncond_tokens = [negative_prompt, negative_prompt_2]
437
+
438
+ negative_prompt_embeds_list = []
439
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
440
+ if isinstance(self, TextualInversionLoaderMixin):
441
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
442
+
443
+ max_length = prompt_embeds.shape[1]
444
+ uncond_input = tokenizer(
445
+ negative_prompt,
446
+ padding="max_length",
447
+ max_length=max_length,
448
+ truncation=True,
449
+ return_tensors="pt",
450
+ )
451
+
452
+ negative_prompt_embeds = text_encoder(
453
+ uncond_input.input_ids.to(device),
454
+ output_hidden_states=True,
455
+ )
456
+ # We are only ALWAYS interested in the pooled output of the final text encoder
457
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
458
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
459
+
460
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
461
+
462
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
463
+
464
+ if self.text_encoder_2 is not None:
465
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
466
+ else:
467
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
468
+
469
+ bs_embed, seq_len, _ = prompt_embeds.shape
470
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
471
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
472
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
473
+
474
+ if do_classifier_free_guidance:
475
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
476
+ seq_len = negative_prompt_embeds.shape[1]
477
+
478
+ if self.text_encoder_2 is not None:
479
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
480
+ else:
481
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
482
+
483
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
484
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
485
+
486
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
487
+ bs_embed * num_images_per_prompt, -1
488
+ )
489
+ if do_classifier_free_guidance:
490
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
491
+ bs_embed * num_images_per_prompt, -1
492
+ )
493
+
494
+ if self.text_encoder is not None:
495
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
496
+ # Retrieve the original scale by scaling back the LoRA layers
497
+ unscale_lora_layers(self.text_encoder, lora_scale)
498
+
499
+ if self.text_encoder_2 is not None:
500
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
501
+ # Retrieve the original scale by scaling back the LoRA layers
502
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
503
+
504
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
505
+
506
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
507
+ def prepare_extra_step_kwargs(self, generator, eta):
508
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
509
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
510
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
511
+ # and should be between [0, 1]
512
+
513
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
514
+ extra_step_kwargs = {}
515
+ if accepts_eta:
516
+ extra_step_kwargs["eta"] = eta
517
+
518
+ # check if the scheduler accepts generator
519
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
520
+ if accepts_generator:
521
+ extra_step_kwargs["generator"] = generator
522
+ return extra_step_kwargs
523
+
524
+ def check_inputs(
525
+ self,
526
+ prompt,
527
+ prompt_2,
528
+ strength,
529
+ num_inference_steps,
530
+ callback_steps,
531
+ negative_prompt=None,
532
+ negative_prompt_2=None,
533
+ prompt_embeds=None,
534
+ negative_prompt_embeds=None,
535
+ ip_adapter_image=None,
536
+ ip_adapter_image_embeds=None,
537
+ callback_on_step_end_tensor_inputs=None,
538
+ ):
539
+ if strength < 0 or strength > 1:
540
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
541
+ if num_inference_steps is None:
542
+ raise ValueError("`num_inference_steps` cannot be None.")
543
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
544
+ raise ValueError(
545
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
546
+ f" {type(num_inference_steps)}."
547
+ )
548
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
549
+ raise ValueError(
550
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
551
+ f" {type(callback_steps)}."
552
+ )
553
+
554
+ if callback_on_step_end_tensor_inputs is not None and not all(
555
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
556
+ ):
557
+ raise ValueError(
558
+ 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]}"
559
+ )
560
+
561
+ if prompt is not None and prompt_embeds is not None:
562
+ raise ValueError(
563
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
564
+ " only forward one of the two."
565
+ )
566
+ elif prompt_2 is not None and prompt_embeds is not None:
567
+ raise ValueError(
568
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
569
+ " only forward one of the two."
570
+ )
571
+ elif prompt is None and prompt_embeds is None:
572
+ raise ValueError(
573
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
574
+ )
575
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
576
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
577
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
578
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
579
+
580
+ if negative_prompt is not None and negative_prompt_embeds is not None:
581
+ raise ValueError(
582
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
583
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
584
+ )
585
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
586
+ raise ValueError(
587
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
588
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
589
+ )
590
+
591
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
592
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
593
+ raise ValueError(
594
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
595
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
596
+ f" {negative_prompt_embeds.shape}."
597
+ )
598
+
599
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
600
+ raise ValueError(
601
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
602
+ )
603
+
604
+ if ip_adapter_image_embeds is not None:
605
+ if not isinstance(ip_adapter_image_embeds, list):
606
+ raise ValueError(
607
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
608
+ )
609
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
610
+ raise ValueError(
611
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
612
+ )
613
+
614
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
615
+ # get the original timestep using init_timestep
616
+ if denoising_start is None:
617
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
618
+ t_start = max(num_inference_steps - init_timestep, 0)
619
+ else:
620
+ t_start = 0
621
+
622
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
623
+
624
+ # Strength is irrelevant if we directly request a timestep to start at;
625
+ # that is, strength is determined by the denoising_start instead.
626
+ if denoising_start is not None:
627
+ discrete_timestep_cutoff = int(
628
+ round(
629
+ self.scheduler.config.num_train_timesteps
630
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
631
+ )
632
+ )
633
+
634
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
635
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
636
+ # if the scheduler is a 2nd order scheduler we might have to do +1
637
+ # because `num_inference_steps` might be even given that every timestep
638
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
639
+ # mean that we cut the timesteps in the middle of the denoising step
640
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
641
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
642
+ num_inference_steps = num_inference_steps + 1
643
+
644
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
645
+ timesteps = timesteps[-num_inference_steps:]
646
+ return timesteps, num_inference_steps
647
+
648
+ return timesteps, num_inference_steps - t_start
649
+
650
+ def prepare_latents(
651
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
652
+ ):
653
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
654
+ raise ValueError(
655
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
656
+ )
657
+
658
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
659
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
660
+ self.text_encoder_2.to("cpu")
661
+ torch.cuda.empty_cache()
662
+
663
+ image = image.to(device=device, dtype=dtype)
664
+
665
+ batch_size = batch_size * num_images_per_prompt
666
+
667
+ if image.shape[1] == 4:
668
+ init_latents = image
669
+
670
+ else:
671
+ # make sure the VAE is in float32 mode, as it overflows in float16
672
+ if self.vae.config.force_upcast:
673
+ image = image.float()
674
+ self.vae.to(dtype=torch.float32)
675
+
676
+ if isinstance(generator, list) and len(generator) != batch_size:
677
+ raise ValueError(
678
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
679
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
680
+ )
681
+
682
+ elif isinstance(generator, list):
683
+ init_latents = [
684
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
685
+ for i in range(batch_size)
686
+ ]
687
+ init_latents = torch.cat(init_latents, dim=0)
688
+ else:
689
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
690
+
691
+ if self.vae.config.force_upcast:
692
+ self.vae.to(dtype)
693
+
694
+ init_latents = init_latents.to(dtype)
695
+ init_latents = self.vae.config.scaling_factor * init_latents
696
+
697
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
698
+ # expand init_latents for batch_size
699
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
700
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
701
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
702
+ raise ValueError(
703
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
704
+ )
705
+ else:
706
+ init_latents = torch.cat([init_latents], dim=0)
707
+
708
+ if add_noise:
709
+ shape = init_latents.shape
710
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
711
+ # get latents
712
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
713
+
714
+ latents = init_latents
715
+
716
+ return latents
717
+
718
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
719
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
720
+ dtype = next(self.image_encoder.parameters()).dtype
721
+
722
+ if not isinstance(image, torch.Tensor):
723
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
724
+
725
+ image = image.to(device=device, dtype=dtype)
726
+ if output_hidden_states:
727
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
728
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
729
+ uncond_image_enc_hidden_states = self.image_encoder(
730
+ torch.zeros_like(image), output_hidden_states=True
731
+ ).hidden_states[-2]
732
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
733
+ num_images_per_prompt, dim=0
734
+ )
735
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
736
+ else:
737
+ image_embeds = self.image_encoder(image).image_embeds
738
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
739
+ uncond_image_embeds = torch.zeros_like(image_embeds)
740
+
741
+ return image_embeds, uncond_image_embeds
742
+
743
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
744
+ def prepare_ip_adapter_image_embeds(
745
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
746
+ ):
747
+ if ip_adapter_image_embeds is None:
748
+ if not isinstance(ip_adapter_image, list):
749
+ ip_adapter_image = [ip_adapter_image]
750
+
751
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
752
+ raise ValueError(
753
+ 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."
754
+ )
755
+
756
+ image_embeds = []
757
+ for single_ip_adapter_image, image_proj_layer in zip(
758
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
759
+ ):
760
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
761
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
762
+ single_ip_adapter_image, device, 1, output_hidden_state
763
+ )
764
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
765
+ single_negative_image_embeds = torch.stack(
766
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
767
+ )
768
+
769
+ if do_classifier_free_guidance:
770
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
771
+ single_image_embeds = single_image_embeds.to(device)
772
+
773
+ image_embeds.append(single_image_embeds)
774
+ else:
775
+ repeat_dims = [1]
776
+ image_embeds = []
777
+ for single_image_embeds in ip_adapter_image_embeds:
778
+ if do_classifier_free_guidance:
779
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
780
+ single_image_embeds = single_image_embeds.repeat(
781
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
782
+ )
783
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
784
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
785
+ )
786
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
787
+ else:
788
+ single_image_embeds = single_image_embeds.repeat(
789
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
790
+ )
791
+ image_embeds.append(single_image_embeds)
792
+
793
+ return image_embeds
794
+
795
+ def _get_add_time_ids(
796
+ self,
797
+ original_size,
798
+ crops_coords_top_left,
799
+ target_size,
800
+ aesthetic_score,
801
+ negative_aesthetic_score,
802
+ negative_original_size,
803
+ negative_crops_coords_top_left,
804
+ negative_target_size,
805
+ dtype,
806
+ text_encoder_projection_dim=None,
807
+ ):
808
+ if self.config.requires_aesthetics_score:
809
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
810
+ add_neg_time_ids = list(
811
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
812
+ )
813
+ else:
814
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
815
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
816
+
817
+ passed_add_embed_dim = (
818
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
819
+ )
820
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
821
+
822
+ if (
823
+ expected_add_embed_dim > passed_add_embed_dim
824
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
825
+ ):
826
+ raise ValueError(
827
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
828
+ )
829
+ elif (
830
+ expected_add_embed_dim < passed_add_embed_dim
831
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
832
+ ):
833
+ raise ValueError(
834
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
835
+ )
836
+ elif expected_add_embed_dim != passed_add_embed_dim:
837
+ raise ValueError(
838
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
839
+ )
840
+
841
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
842
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
843
+
844
+ return add_time_ids, add_neg_time_ids
845
+
846
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
847
+ def upcast_vae(self):
848
+ dtype = self.vae.dtype
849
+ self.vae.to(dtype=torch.float32)
850
+ use_torch_2_0_or_xformers = isinstance(
851
+ self.vae.decoder.mid_block.attentions[0].processor,
852
+ (
853
+ AttnProcessor2_0,
854
+ XFormersAttnProcessor,
855
+ ),
856
+ )
857
+ # if xformers or torch_2_0 is used attention block does not need
858
+ # to be in float32 which can save lots of memory
859
+ if use_torch_2_0_or_xformers:
860
+ self.vae.post_quant_conv.to(dtype)
861
+ self.vae.decoder.conv_in.to(dtype)
862
+ self.vae.decoder.mid_block.to(dtype)
863
+
864
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
865
+ def get_guidance_scale_embedding(
866
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
867
+ ) -> torch.Tensor:
868
+ """
869
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
870
+
871
+ Args:
872
+ w (`torch.Tensor`):
873
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
874
+ embedding_dim (`int`, *optional*, defaults to 512):
875
+ Dimension of the embeddings to generate.
876
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
877
+ Data type of the generated embeddings.
878
+
879
+ Returns:
880
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
881
+ """
882
+ assert len(w.shape) == 1
883
+ w = w * 1000.0
884
+
885
+ half_dim = embedding_dim // 2
886
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
887
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
888
+ emb = w.to(dtype)[:, None] * emb[None, :]
889
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
890
+ if embedding_dim % 2 == 1: # zero pad
891
+ emb = torch.nn.functional.pad(emb, (0, 1))
892
+ assert emb.shape == (w.shape[0], embedding_dim)
893
+ return emb
894
+
895
+ @property
896
+ def guidance_scale(self):
897
+ return self._guidance_scale
898
+
899
+ @property
900
+ def guidance_rescale(self):
901
+ return self._guidance_rescale
902
+
903
+ @property
904
+ def clip_skip(self):
905
+ return self._clip_skip
906
+
907
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
908
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
909
+ # corresponds to doing no classifier free guidance.
910
+ @property
911
+ def do_classifier_free_guidance(self):
912
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
913
+
914
+ @property
915
+ def cross_attention_kwargs(self):
916
+ return self._cross_attention_kwargs
917
+
918
+ @property
919
+ def denoising_end(self):
920
+ return self._denoising_end
921
+
922
+ @property
923
+ def denoising_start(self):
924
+ return self._denoising_start
925
+
926
+ @property
927
+ def num_timesteps(self):
928
+ return self._num_timesteps
929
+
930
+ @property
931
+ def interrupt(self):
932
+ return self._interrupt
933
+
934
+ @torch.no_grad()
935
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
936
+ def __call__(
937
+ self,
938
+ prompt: Union[str, List[str]] = None,
939
+ prompt_2: Optional[Union[str, List[str]]] = None,
940
+ image: Union[
941
+ torch.Tensor,
942
+ PIL.Image.Image,
943
+ np.ndarray,
944
+ List[torch.Tensor],
945
+ List[PIL.Image.Image],
946
+ List[np.ndarray],
947
+ ] = None,
948
+ strength: float = 0.3,
949
+ num_inference_steps: int = 50,
950
+ timesteps: List[int] = None,
951
+ denoising_start: Optional[float] = None,
952
+ denoising_end: Optional[float] = None,
953
+ guidance_scale: float = 5.0,
954
+ negative_prompt: Optional[Union[str, List[str]]] = None,
955
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
956
+ num_images_per_prompt: Optional[int] = 1,
957
+ eta: float = 0.0,
958
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
959
+ latents: Optional[torch.Tensor] = None,
960
+ prompt_embeds: Optional[torch.Tensor] = None,
961
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
962
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
963
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
964
+ ip_adapter_image: Optional[PipelineImageInput] = None,
965
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
966
+ output_type: Optional[str] = "pil",
967
+ return_dict: bool = True,
968
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
969
+ guidance_rescale: float = 0.0,
970
+ original_size: Tuple[int, int] = None,
971
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
972
+ target_size: Tuple[int, int] = None,
973
+ negative_original_size: Optional[Tuple[int, int]] = None,
974
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
975
+ negative_target_size: Optional[Tuple[int, int]] = None,
976
+ aesthetic_score: float = 6.0,
977
+ negative_aesthetic_score: float = 2.5,
978
+ clip_skip: Optional[int] = None,
979
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
980
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
981
+ map: torch.Tensor = None,
982
+ original_image: Union[
983
+ torch.Tensor,
984
+ PIL.Image.Image,
985
+ np.ndarray,
986
+ List[torch.Tensor],
987
+ List[PIL.Image.Image],
988
+ List[np.ndarray],
989
+ ] = None,
990
+ **kwargs,
991
+ ):
992
+ r"""
993
+ Function invoked when calling the pipeline for generation.
994
+
995
+ Args:
996
+ prompt (`str` or `List[str]`, *optional*):
997
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
998
+ instead.
999
+ prompt_2 (`str` or `List[str]`, *optional*):
1000
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1001
+ used in both text-encoders
1002
+ image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
1003
+ The image(s) to modify with the pipeline.
1004
+ strength (`float`, *optional*, defaults to 0.3):
1005
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
1006
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
1007
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
1008
+ be maximum and the denoising process will run for the full number of iterations specified in
1009
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
1010
+ `denoising_start` being declared as an integer, the value of `strength` will be ignored.
1011
+ num_inference_steps (`int`, *optional*, defaults to 50):
1012
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1013
+ expense of slower inference.
1014
+ denoising_start (`float`, *optional*):
1015
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1016
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1017
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1018
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1019
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image
1020
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1021
+ denoising_end (`float`, *optional*):
1022
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1023
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1024
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1025
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1026
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1027
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1028
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1029
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1030
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1031
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1032
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1033
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1034
+ usually at the expense of lower image quality.
1035
+ negative_prompt (`str` or `List[str]`, *optional*):
1036
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1037
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1038
+ less than `1`).
1039
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1040
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1041
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1042
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1043
+ The number of images to generate per prompt.
1044
+ eta (`float`, *optional*, defaults to 0.0):
1045
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1046
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1047
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1048
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1049
+ to make generation deterministic.
1050
+ latents (`torch.Tensor`, *optional*):
1051
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1052
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1053
+ tensor will ge generated by sampling using the supplied random `generator`.
1054
+ prompt_embeds (`torch.Tensor`, *optional*):
1055
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1056
+ provided, text embeddings will be generated from `prompt` input argument.
1057
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1058
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1059
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1060
+ argument.
1061
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1062
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1063
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1064
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1065
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1066
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1067
+ input argument.
1068
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1069
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1070
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
1071
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
1072
+ if `do_classifier_free_guidance` is set to `True`.
1073
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
1074
+ output_type (`str`, *optional*, defaults to `"pil"`):
1075
+ The output format of the generate image. Choose between
1076
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1077
+ return_dict (`bool`, *optional*, defaults to `True`):
1078
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
1079
+ plain tuple.
1080
+ callback (`Callable`, *optional*):
1081
+ A function that will be called every `callback_steps` steps during inference. The function will be
1082
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
1083
+ callback_steps (`int`, *optional*, defaults to 1):
1084
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1085
+ called at every step.
1086
+ cross_attention_kwargs (`dict`, *optional*):
1087
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1088
+ `self.processor` in
1089
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
1090
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
1091
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1092
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1093
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1094
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1095
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1096
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1097
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
1098
+ explained in section 2.2 of
1099
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1100
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1101
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1102
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1103
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1104
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1105
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1106
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1107
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
1108
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1109
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1110
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1111
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1112
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1113
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1114
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1115
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1116
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1117
+
1118
+ Examples:
1119
+
1120
+ Returns:
1121
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1122
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1123
+ `tuple. When returning a tuple, the first element is a list with the generated images.
1124
+ """
1125
+
1126
+ callback = kwargs.pop("callback", None)
1127
+ callback_steps = kwargs.pop("callback_steps", None)
1128
+
1129
+ if callback is not None:
1130
+ deprecate(
1131
+ "callback",
1132
+ "1.0.0",
1133
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1134
+ )
1135
+ if callback_steps is not None:
1136
+ deprecate(
1137
+ "callback_steps",
1138
+ "1.0.0",
1139
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1140
+ )
1141
+
1142
+ # 1. Check inputs. Raise error if not correct
1143
+ self.check_inputs(
1144
+ prompt,
1145
+ prompt_2,
1146
+ strength,
1147
+ num_inference_steps,
1148
+ callback_steps,
1149
+ negative_prompt,
1150
+ negative_prompt_2,
1151
+ prompt_embeds,
1152
+ negative_prompt_embeds,
1153
+ ip_adapter_image,
1154
+ ip_adapter_image_embeds,
1155
+ callback_on_step_end_tensor_inputs,
1156
+ )
1157
+
1158
+ self._guidance_scale = guidance_scale
1159
+ self._guidance_rescale = guidance_rescale
1160
+ self._clip_skip = clip_skip
1161
+ self._cross_attention_kwargs = cross_attention_kwargs
1162
+ self._denoising_end = denoising_end
1163
+ self._denoising_start = denoising_start
1164
+ self._interrupt = False
1165
+
1166
+ # 2. Define call parameters
1167
+ if prompt is not None and isinstance(prompt, str):
1168
+ batch_size = 1
1169
+ elif prompt is not None and isinstance(prompt, list):
1170
+ batch_size = len(prompt)
1171
+ else:
1172
+ batch_size = prompt_embeds.shape[0]
1173
+
1174
+ device = self._execution_device
1175
+
1176
+ # 3. Encode input prompt
1177
+ text_encoder_lora_scale = (
1178
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1179
+ )
1180
+ (
1181
+ prompt_embeds,
1182
+ negative_prompt_embeds,
1183
+ pooled_prompt_embeds,
1184
+ negative_pooled_prompt_embeds,
1185
+ ) = self.encode_prompt(
1186
+ prompt=prompt,
1187
+ prompt_2=prompt_2,
1188
+ device=device,
1189
+ num_images_per_prompt=num_images_per_prompt,
1190
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1191
+ negative_prompt=negative_prompt,
1192
+ negative_prompt_2=negative_prompt_2,
1193
+ prompt_embeds=prompt_embeds,
1194
+ negative_prompt_embeds=negative_prompt_embeds,
1195
+ pooled_prompt_embeds=pooled_prompt_embeds,
1196
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1197
+ lora_scale=text_encoder_lora_scale,
1198
+ )
1199
+
1200
+ # 4. Preprocess image
1201
+ # image = self.image_processor.preprocess(image) #ideally we would have preprocess the image with diffusers, but for this POC we won't --- it throws a deprecated warning
1202
+ map = torchvision.transforms.Resize(
1203
+ tuple(s // self.vae_scale_factor for s in original_image.shape[2:]), antialias=None
1204
+ )(map)
1205
+
1206
+ # 5. Prepare timesteps
1207
+ def denoising_value_valid(dnv):
1208
+ return isinstance(dnv, float) and 0 < dnv < 1
1209
+
1210
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1211
+
1212
+ # begin diff diff change
1213
+ total_time_steps = num_inference_steps
1214
+ # end diff diff change
1215
+
1216
+ timesteps, num_inference_steps = self.get_timesteps(
1217
+ num_inference_steps,
1218
+ strength,
1219
+ device,
1220
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1221
+ )
1222
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1223
+
1224
+ add_noise = True if denoising_start is None else False
1225
+ # 6. Prepare latent variables
1226
+ latents = self.prepare_latents(
1227
+ image,
1228
+ latent_timestep,
1229
+ batch_size,
1230
+ num_images_per_prompt,
1231
+ prompt_embeds.dtype,
1232
+ device,
1233
+ generator,
1234
+ add_noise,
1235
+ )
1236
+ # 7. Prepare extra step kwargs.
1237
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1238
+
1239
+ height, width = latents.shape[-2:]
1240
+ height = height * self.vae_scale_factor
1241
+ width = width * self.vae_scale_factor
1242
+
1243
+ original_size = original_size or (height, width)
1244
+ target_size = target_size or (height, width)
1245
+
1246
+ # 8. Prepare added time ids & embeddings
1247
+ if negative_original_size is None:
1248
+ negative_original_size = original_size
1249
+ if negative_target_size is None:
1250
+ negative_target_size = target_size
1251
+
1252
+ add_text_embeds = pooled_prompt_embeds
1253
+ if self.text_encoder_2 is None:
1254
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1255
+ else:
1256
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1257
+
1258
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1259
+ original_size,
1260
+ crops_coords_top_left,
1261
+ target_size,
1262
+ aesthetic_score,
1263
+ negative_aesthetic_score,
1264
+ negative_original_size,
1265
+ negative_crops_coords_top_left,
1266
+ negative_target_size,
1267
+ dtype=prompt_embeds.dtype,
1268
+ text_encoder_projection_dim=text_encoder_projection_dim,
1269
+ )
1270
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1271
+
1272
+ if self.do_classifier_free_guidance:
1273
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1274
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1275
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1276
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1277
+
1278
+ prompt_embeds = prompt_embeds.to(device)
1279
+ add_text_embeds = add_text_embeds.to(device)
1280
+ add_time_ids = add_time_ids.to(device)
1281
+
1282
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1283
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1284
+ ip_adapter_image,
1285
+ ip_adapter_image_embeds,
1286
+ device,
1287
+ batch_size * num_images_per_prompt,
1288
+ self.do_classifier_free_guidance,
1289
+ )
1290
+
1291
+ # 9. Denoising loop
1292
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1293
+
1294
+ # 9.1 Apply denoising_end
1295
+ if (
1296
+ denoising_end is not None
1297
+ and denoising_start is not None
1298
+ and denoising_value_valid(denoising_end)
1299
+ and denoising_value_valid(denoising_start)
1300
+ and denoising_start >= denoising_end
1301
+ ):
1302
+ raise ValueError(
1303
+ f"`denoising_start`: {denoising_start} cannot be larger than or equal to `denoising_end`: "
1304
+ + f" {denoising_end} when using type float."
1305
+ )
1306
+ elif denoising_end is not None and denoising_value_valid(denoising_end):
1307
+ discrete_timestep_cutoff = int(
1308
+ round(
1309
+ self.scheduler.config.num_train_timesteps
1310
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
1311
+ )
1312
+ )
1313
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1314
+ timesteps = timesteps[:num_inference_steps]
1315
+
1316
+ # preparations for diff diff
1317
+ original_with_noise = self.prepare_latents(
1318
+ original_image, timesteps, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
1319
+ )
1320
+ thresholds = torch.arange(total_time_steps, dtype=map.dtype) / total_time_steps
1321
+ thresholds = thresholds.unsqueeze(1).unsqueeze(1).to(device)
1322
+ masks = map > (thresholds + (denoising_start or 0))
1323
+ # end diff diff preparations
1324
+
1325
+ # 9.2 Optionally get Guidance Scale Embedding
1326
+ timestep_cond = None
1327
+ if self.unet.config.time_cond_proj_dim is not None:
1328
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1329
+ timestep_cond = self.get_guidance_scale_embedding(
1330
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1331
+ ).to(device=device, dtype=latents.dtype)
1332
+
1333
+ self._num_timesteps = len(timesteps)
1334
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1335
+ for i, t in enumerate(timesteps):
1336
+ if self.interrupt:
1337
+ continue
1338
+
1339
+ # diff diff
1340
+ if i == 0 and denoising_start is None:
1341
+ latents = original_with_noise[:1]
1342
+ else:
1343
+ mask = masks[i].unsqueeze(0)
1344
+ # cast mask to the same type as latents etc
1345
+ mask = mask.to(latents.dtype)
1346
+ mask = mask.unsqueeze(1) # fit shape
1347
+ latents = original_with_noise[i] * mask + latents * (1 - mask)
1348
+ # end diff diff
1349
+
1350
+ # expand the latents if we are doing classifier free guidance
1351
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1352
+
1353
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1354
+
1355
+ # predict the noise residual
1356
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1357
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1358
+ added_cond_kwargs["image_embeds"] = image_embeds
1359
+ noise_pred = self.unet(
1360
+ latent_model_input,
1361
+ t,
1362
+ encoder_hidden_states=prompt_embeds,
1363
+ timestep_cond=timestep_cond,
1364
+ cross_attention_kwargs=cross_attention_kwargs,
1365
+ added_cond_kwargs=added_cond_kwargs,
1366
+ return_dict=False,
1367
+ )[0]
1368
+
1369
+ # perform guidance
1370
+ if self.do_classifier_free_guidance:
1371
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1372
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1373
+
1374
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
1375
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1376
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1377
+
1378
+ # compute the previous noisy sample x_t -> x_t-1
1379
+ latents_dtype = latents.dtype
1380
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1381
+ if latents.dtype != latents_dtype:
1382
+ if torch.backends.mps.is_available():
1383
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1384
+ latents = latents.to(latents_dtype)
1385
+ else:
1386
+ raise ValueError(
1387
+ "For the given accelerator, there seems to be an unexpected problem in type-casting. Please file an issue on the PyTorch GitHub repository. See also: https://github.com/huggingface/diffusers/pull/7446/."
1388
+ )
1389
+
1390
+ if callback_on_step_end is not None:
1391
+ callback_kwargs = {}
1392
+ for k in callback_on_step_end_tensor_inputs:
1393
+ callback_kwargs[k] = locals()[k]
1394
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1395
+
1396
+ if callback_outputs is not None:
1397
+ latents = callback_outputs.pop("latents", latents)
1398
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1399
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1400
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1401
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1402
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1403
+ )
1404
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1405
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1406
+
1407
+ # call the callback, if provided
1408
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1409
+ progress_bar.update()
1410
+ if callback is not None and i % callback_steps == 0:
1411
+ step_idx = i // getattr(self.scheduler, "order", 1)
1412
+ callback(step_idx, t, latents)
1413
+
1414
+ if XLA_AVAILABLE:
1415
+ xm.mark_step()
1416
+
1417
+ if not output_type == "latent":
1418
+ # make sure the VAE is in float32 mode, as it overflows in float16
1419
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1420
+
1421
+ if needs_upcasting:
1422
+ self.upcast_vae()
1423
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1424
+ elif latents.dtype != self.vae.dtype:
1425
+ if torch.backends.mps.is_available():
1426
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1427
+ self.vae = self.vae.to(latents.dtype)
1428
+ else:
1429
+ raise ValueError(
1430
+ "For the given accelerator, there seems to be an unexpected problem in type-casting. Please file an issue on the PyTorch GitHub repository. See also: https://github.com/huggingface/diffusers/pull/7446/."
1431
+ )
1432
+ # unscale/denormalize the latents
1433
+ # denormalize with the mean and std if available and not None
1434
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1435
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1436
+ if has_latents_mean and has_latents_std:
1437
+ latents_mean = (
1438
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1439
+ )
1440
+ latents_std = (
1441
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1442
+ )
1443
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1444
+ else:
1445
+ latents = latents / self.vae.config.scaling_factor
1446
+
1447
+ image = self.vae.decode(latents, return_dict=False)[0]
1448
+
1449
+ # cast back to fp16 if needed
1450
+ if needs_upcasting:
1451
+ self.vae.to(dtype=torch.float16)
1452
+ else:
1453
+ image = latents
1454
+
1455
+ # apply watermark if available
1456
+ if self.watermark is not None:
1457
+ image = self.watermark.apply_watermark(image)
1458
+
1459
+ image = self.image_processor.postprocess(image, output_type=output_type)
1460
+
1461
+ # Offload all models
1462
+ self.maybe_free_model_hooks()
1463
+
1464
+ if not return_dict:
1465
+ return (image,)
1466
+
1467
+ return StableDiffusionXLPipelineOutput(images=image)