Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
e9d361a
·
verified ·
1 Parent(s): 4024e51

Upload folder using huggingface_hub

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