optimum-rbln 0.1.0__py3-none-any.whl → 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. optimum/rbln/__init__.py +6 -0
  2. optimum/rbln/__version__.py +1 -1
  3. optimum/rbln/diffusers/__init__.py +7 -0
  4. optimum/rbln/diffusers/models/autoencoder_kl.py +30 -9
  5. optimum/rbln/diffusers/models/controlnet.py +93 -23
  6. optimum/rbln/diffusers/models/unet_2d_condition.py +78 -61
  7. optimum/rbln/diffusers/pipelines/__init__.py +7 -2
  8. optimum/rbln/diffusers/pipelines/controlnet/__init__.py +4 -0
  9. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +768 -0
  10. optimum/rbln/diffusers/pipelines/{stable_diffusion → controlnet}/pipeline_controlnet_img2img.py +25 -16
  11. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +942 -0
  12. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +955 -0
  13. optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +0 -1
  14. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -4
  15. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +22 -9
  16. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +19 -3
  17. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +19 -3
  18. optimum/rbln/modeling_base.py +36 -3
  19. optimum/rbln/modeling_seq2seq.py +19 -4
  20. optimum/rbln/transformers/generation/__init__.py +1 -0
  21. optimum/rbln/transformers/generation/streamers.py +17 -0
  22. optimum/rbln/transformers/generation/utils.py +399 -0
  23. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +24 -333
  24. optimum/rbln/transformers/models/llama/modeling_llama.py +63 -45
  25. optimum/rbln/transformers/models/whisper/modeling_whisper.py +13 -3
  26. {optimum_rbln-0.1.0.dist-info → optimum_rbln-0.1.1.dist-info}/METADATA +1 -1
  27. {optimum_rbln-0.1.0.dist-info → optimum_rbln-0.1.1.dist-info}/RECORD +29 -25
  28. {optimum_rbln-0.1.0.dist-info → optimum_rbln-0.1.1.dist-info}/WHEEL +0 -0
  29. {optimum_rbln-0.1.0.dist-info → optimum_rbln-0.1.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,942 @@
1
+ # Copyright 2024 Rebellions Inc.
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
+ # Portions of this software are licensed under the Apache License,
16
+ # Version 2.0. See the NOTICE file distributed with this work for
17
+ # additional information regarding copyright ownership.
18
+
19
+ # All other portions of this software, including proprietary code,
20
+ # are the intellectual property of Rebellions Inc. and may not be
21
+ # copied, modified, or distributed without prior written permission
22
+ # from Rebellions Inc.
23
+ """RBLNStableDiffusionXLPipeline class for inference of diffusion models on rbln devices."""
24
+
25
+ from pathlib import Path
26
+ from tempfile import TemporaryDirectory
27
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
28
+
29
+ import torch
30
+ import torch.nn.functional as F
31
+ from diffusers import StableDiffusionXLControlNetPipeline
32
+ from diffusers.image_processor import PipelineImageInput
33
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
34
+ from diffusers.utils import deprecate, logging
35
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version
36
+
37
+ from ....modeling_base import RBLNBaseModel
38
+ from ....transformers import RBLNCLIPTextModel, RBLNCLIPTextModelWithProjection
39
+ from ...models import RBLNAutoencoderKL, RBLNControlNetModel, RBLNUNet2DConditionModel
40
+ from ...pipelines.controlnet.multicontrolnet import RBLNMultiControlNetModel
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class RBLNStableDiffusionXLControlNetPipeline(StableDiffusionXLControlNetPipeline):
47
+ @classmethod
48
+ def from_pretrained(cls, model_id, **kwargs):
49
+ """
50
+ Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet.
51
+
52
+ This model inherits from [`StableDiffusionXLControlNetPipeline`]. Check the superclass documentation for the generic methods
53
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
54
+
55
+ It implements the methods to convert a pre-trained Stable Diffusion XL Controlnet pipeline into a RBLNStableDiffusionXLControlNet pipeline by:
56
+ - transferring the checkpoint weights of the original into an optimized RBLN graph,
57
+ - compiling the resulting graph using the RBLN compiler.
58
+
59
+ Args:
60
+ model_id (`Union[str, Path]`):
61
+ Can be either:
62
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
63
+ - A path to a *directory* containing a model saved using [`~OptimizedModel.save_pretrained`],
64
+ """
65
+ export = kwargs.pop("export", None)
66
+ text_encoder = kwargs.pop("text_encoder", None)
67
+ controlnets = kwargs.pop("controlnet", None)
68
+ vae = kwargs.pop("vae", None)
69
+
70
+ rbln_config_kwargs, rbln_constructor_kwargs = RBLNBaseModel.pop_rbln_kwargs_from_kwargs(kwargs)
71
+ kwargs_dict = {
72
+ "pretrained_model_name_or_path": model_id,
73
+ "vae": vae,
74
+ "controlnet": controlnets,
75
+ "text_encoder": text_encoder,
76
+ **kwargs,
77
+ }
78
+
79
+ model = super().from_pretrained(**{k: v for k, v in kwargs_dict.items() if v is not None})
80
+
81
+ if export is None or export is False:
82
+ return model
83
+
84
+ save_dir = TemporaryDirectory()
85
+ save_dir_path = Path(save_dir.name)
86
+
87
+ model.save_pretrained(save_directory=save_dir_path, **kwargs)
88
+
89
+ do_classifier_free_guidance = (
90
+ rbln_config_kwargs.pop("rbln_guidance_scale", 5.0) > 1.0 and model.unet.config.time_cond_proj_dim is None
91
+ )
92
+
93
+ vae = RBLNAutoencoderKL.from_pretrained(
94
+ model_id=model_id,
95
+ subfolder="vae",
96
+ export=True,
97
+ rbln_unet_sample_size=model.unet.config.sample_size,
98
+ rbln_use_encode=True,
99
+ rbln_vae_scale_factor=model.vae_scale_factor,
100
+ **rbln_config_kwargs,
101
+ **rbln_constructor_kwargs,
102
+ )
103
+ text_encoder = RBLNCLIPTextModel.from_pretrained(
104
+ model_id=model_id,
105
+ subfolder="text_encoder",
106
+ export=True,
107
+ **rbln_config_kwargs,
108
+ **rbln_constructor_kwargs,
109
+ )
110
+ text_encoder_2 = RBLNCLIPTextModelWithProjection.from_pretrained(
111
+ model_id=model_id,
112
+ subfolder="text_encoder_2",
113
+ export=True,
114
+ **rbln_config_kwargs,
115
+ **rbln_constructor_kwargs,
116
+ )
117
+
118
+ batch_size = rbln_config_kwargs.pop("rbln_batch_size", 1)
119
+ unet_batch_size = batch_size * 2 if do_classifier_free_guidance else batch_size
120
+
121
+ unet = RBLNUNet2DConditionModel.from_pretrained(
122
+ model_id=model_id,
123
+ subfolder="unet",
124
+ export=True,
125
+ rbln_max_seq_len=model.text_encoder.config.max_position_embeddings,
126
+ rbln_text_model_hidden_size=model.text_encoder_2.config.hidden_size,
127
+ rbln_batch_size=unet_batch_size,
128
+ rbln_use_encode=True,
129
+ rbln_vae_scale_factor=model.vae_scale_factor,
130
+ rbln_is_controlnet=True if "controlnet" in model.config.keys() else False,
131
+ **rbln_config_kwargs,
132
+ **rbln_constructor_kwargs,
133
+ )
134
+
135
+ if isinstance(controlnets, (list, tuple)):
136
+ controlnet = RBLNMultiControlNetModel.from_pretrained(
137
+ model_id=str(save_dir_path / "controlnet"),
138
+ export=True,
139
+ rbln_batch_size=unet_batch_size,
140
+ rbln_vae_scale_factor=model.vae_scale_factor,
141
+ **rbln_config_kwargs,
142
+ **rbln_constructor_kwargs,
143
+ )
144
+ controlnet_dict = ("optimum.rbln", "RBLNMultiControlNetModel")
145
+ else:
146
+ controlnet = RBLNControlNetModel.from_pretrained(
147
+ model_id=save_dir_path / "controlnet",
148
+ export=True,
149
+ rbln_batch_size=unet_batch_size,
150
+ rbln_text_model_hidden_size=model.text_encoder_2.config.hidden_size,
151
+ rbln_vae_scale_factor=model.vae_scale_factor,
152
+ **rbln_config_kwargs,
153
+ **rbln_constructor_kwargs,
154
+ )
155
+ controlnet_dict = ("optimum.rbln", "RBLNControlNetModel")
156
+
157
+ model.vae = vae
158
+ model.text_encoder = text_encoder
159
+ model.unet = unet
160
+ model.text_encoder_2 = text_encoder_2
161
+ model.controlnet = controlnet
162
+
163
+ update_dict = {
164
+ "vae": ("optimum.rbln", "RBLNAutoencoderKL"),
165
+ "text_encoder": ("optimum.rbln", "RBLNCLIPTextModel"),
166
+ "unet": ("optimum.rbln", "RBLNUNet2DConditionModel"),
167
+ "text_encoder_2": ("optimum.rbln", "RBLNCLIPTextModel"),
168
+ "controlnet": controlnet_dict,
169
+ }
170
+ model.register_to_config(**update_dict)
171
+
172
+ model.models = [
173
+ vae.model[0],
174
+ unet.model[0],
175
+ text_encoder.model[0],
176
+ text_encoder_2.model[0],
177
+ controlnet.model[0],
178
+ ]
179
+
180
+ return model
181
+
182
+ def check_inputs(
183
+ self,
184
+ prompt,
185
+ prompt_2,
186
+ image,
187
+ callback_steps,
188
+ negative_prompt=None,
189
+ negative_prompt_2=None,
190
+ prompt_embeds=None,
191
+ negative_prompt_embeds=None,
192
+ pooled_prompt_embeds=None,
193
+ ip_adapter_image=None,
194
+ ip_adapter_image_embeds=None,
195
+ negative_pooled_prompt_embeds=None,
196
+ controlnet_conditioning_scale=1.0,
197
+ control_guidance_start=0.0,
198
+ control_guidance_end=1.0,
199
+ callback_on_step_end_tensor_inputs=None,
200
+ ):
201
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
202
+ raise ValueError(
203
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
204
+ f" {type(callback_steps)}."
205
+ )
206
+
207
+ if callback_on_step_end_tensor_inputs is not None and not all(
208
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
209
+ ):
210
+ raise ValueError(
211
+ 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]}"
212
+ )
213
+
214
+ if prompt is not None and prompt_embeds is not None:
215
+ raise ValueError(
216
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
217
+ " only forward one of the two."
218
+ )
219
+ elif prompt_2 is not None and prompt_embeds is not None:
220
+ raise ValueError(
221
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
222
+ " only forward one of the two."
223
+ )
224
+ elif prompt is None and prompt_embeds is None:
225
+ raise ValueError(
226
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
227
+ )
228
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
229
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
230
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
231
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
232
+
233
+ if negative_prompt is not None and negative_prompt_embeds is not None:
234
+ raise ValueError(
235
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
236
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
237
+ )
238
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
239
+ raise ValueError(
240
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
241
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
242
+ )
243
+
244
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
245
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
246
+ raise ValueError(
247
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
248
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
249
+ f" {negative_prompt_embeds.shape}."
250
+ )
251
+
252
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
253
+ raise ValueError(
254
+ "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`."
255
+ )
256
+
257
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
258
+ raise ValueError(
259
+ "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`."
260
+ )
261
+
262
+ # `prompt` needs more sophisticated handling when there are multiple
263
+ # conditionings.
264
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
265
+ if isinstance(prompt, list):
266
+ logger.warning(
267
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
268
+ " prompts. The conditionings will be fixed across the prompts."
269
+ )
270
+
271
+ # Check `image`
272
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
273
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
274
+ )
275
+ if (
276
+ isinstance(self.controlnet, RBLNControlNetModel)
277
+ or is_compiled
278
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
279
+ ):
280
+ self.check_image(image, prompt, prompt_embeds)
281
+ elif (
282
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
283
+ or is_compiled
284
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
285
+ ):
286
+ if not isinstance(image, list):
287
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
288
+
289
+ # When `image` is a nested list:
290
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
291
+ elif any(isinstance(i, list) for i in image):
292
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
293
+ elif len(image) != len(self.controlnet.nets):
294
+ raise ValueError(
295
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
296
+ )
297
+
298
+ for image_ in image:
299
+ self.check_image(image_, prompt, prompt_embeds)
300
+ else:
301
+ assert False
302
+
303
+ # Check `controlnet_conditioning_scale`
304
+ if (
305
+ isinstance(self.controlnet, RBLNControlNetModel)
306
+ or is_compiled
307
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
308
+ ):
309
+ if not isinstance(controlnet_conditioning_scale, float):
310
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
311
+ elif (
312
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
313
+ or is_compiled
314
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
315
+ ):
316
+ if isinstance(controlnet_conditioning_scale, list):
317
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
318
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
319
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
320
+ self.controlnet.nets
321
+ ):
322
+ raise ValueError(
323
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
324
+ " the same length as the number of controlnets"
325
+ )
326
+ else:
327
+ assert False
328
+
329
+ if not isinstance(control_guidance_start, (tuple, list)):
330
+ control_guidance_start = [control_guidance_start]
331
+
332
+ if not isinstance(control_guidance_end, (tuple, list)):
333
+ control_guidance_end = [control_guidance_end]
334
+
335
+ if len(control_guidance_start) != len(control_guidance_end):
336
+ raise ValueError(
337
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
338
+ )
339
+
340
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
341
+ if len(control_guidance_start) != len(self.controlnet.nets):
342
+ raise ValueError(
343
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
344
+ )
345
+
346
+ for start, end in zip(control_guidance_start, control_guidance_end):
347
+ if start >= end:
348
+ raise ValueError(
349
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
350
+ )
351
+ if start < 0.0:
352
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
353
+ if end > 1.0:
354
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
355
+
356
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
357
+ raise ValueError(
358
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
359
+ )
360
+
361
+ if ip_adapter_image_embeds is not None:
362
+ if not isinstance(ip_adapter_image_embeds, list):
363
+ raise ValueError(
364
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
365
+ )
366
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
367
+ raise ValueError(
368
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
369
+ )
370
+
371
+ @torch.no_grad()
372
+ def __call__(
373
+ self,
374
+ prompt: Union[str, List[str]] = None,
375
+ prompt_2: Optional[Union[str, List[str]]] = None,
376
+ image: PipelineImageInput = None,
377
+ height: Optional[int] = None,
378
+ width: Optional[int] = None,
379
+ num_inference_steps: int = 50,
380
+ denoising_end: Optional[float] = None,
381
+ guidance_scale: float = 5.0,
382
+ negative_prompt: Optional[Union[str, List[str]]] = None,
383
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
384
+ num_images_per_prompt: Optional[int] = 1,
385
+ eta: float = 0.0,
386
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
387
+ latents: Optional[torch.FloatTensor] = None,
388
+ prompt_embeds: Optional[torch.FloatTensor] = None,
389
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
390
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
391
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
392
+ ip_adapter_image: Optional[PipelineImageInput] = None,
393
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
394
+ output_type: Optional[str] = "pil",
395
+ return_dict: bool = True,
396
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
397
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
398
+ guess_mode: bool = False,
399
+ control_guidance_start: Union[float, List[float]] = 0.0,
400
+ control_guidance_end: Union[float, List[float]] = 1.0,
401
+ original_size: Tuple[int, int] = None,
402
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
403
+ target_size: Tuple[int, int] = None,
404
+ negative_original_size: Optional[Tuple[int, int]] = None,
405
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
406
+ negative_target_size: Optional[Tuple[int, int]] = None,
407
+ clip_skip: Optional[int] = None,
408
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
409
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
410
+ **kwargs,
411
+ ):
412
+ r"""
413
+ The call function to the pipeline for generation.
414
+
415
+ Args:
416
+ prompt (`str` or `List[str]`, *optional*):
417
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
418
+ prompt_2 (`str` or `List[str]`, *optional*):
419
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
420
+ used in both text-encoders.
421
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
422
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
423
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
424
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
425
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
426
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
427
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
428
+ input to a single ControlNet.
429
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
430
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
431
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
432
+ and checkpoints that are not specifically fine-tuned on low resolutions.
433
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
434
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
435
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
436
+ and checkpoints that are not specifically fine-tuned on low resolutions.
437
+ num_inference_steps (`int`, *optional*, defaults to 50):
438
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
439
+ expense of slower inference.
440
+ denoising_end (`float`, *optional*):
441
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
442
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
443
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
444
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
445
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
446
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
447
+ guidance_scale (`float`, *optional*, defaults to 5.0):
448
+ A higher guidance scale value encourages the model to generate images closely linked to the text
449
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
450
+ negative_prompt (`str` or `List[str]`, *optional*):
451
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
452
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
453
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
454
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
455
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
456
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
457
+ The number of images to generate per prompt.
458
+ eta (`float`, *optional*, defaults to 0.0):
459
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
460
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
461
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
462
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
463
+ generation deterministic.
464
+ latents (`torch.FloatTensor`, *optional*):
465
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
466
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
467
+ tensor is generated by sampling using the supplied random `generator`.
468
+ prompt_embeds (`torch.FloatTensor`, *optional*):
469
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
470
+ provided, text embeddings are generated from the `prompt` input argument.
471
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
472
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
473
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
474
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
475
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
476
+ not provided, pooled text embeddings are generated from `prompt` input argument.
477
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
478
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
479
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
480
+ argument.
481
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
482
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
483
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
484
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
485
+ if `do_classifier_free_guidance` is set to `True`.
486
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
487
+ output_type (`str`, *optional*, defaults to `"pil"`):
488
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
489
+ return_dict (`bool`, *optional*, defaults to `True`):
490
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
491
+ plain tuple.
492
+ cross_attention_kwargs (`dict`, *optional*):
493
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
494
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
495
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
496
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
497
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
498
+ the corresponding scale as a list.
499
+ guess_mode (`bool`, *optional*, defaults to `False`):
500
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
501
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
502
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
503
+ The percentage of total steps at which the ControlNet starts applying.
504
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
505
+ The percentage of total steps at which the ControlNet stops applying.
506
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
507
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
508
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
509
+ explained in section 2.2 of
510
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
511
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
512
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
513
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
514
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
515
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
516
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
517
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
518
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
519
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
520
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
521
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
522
+ micro-conditioning as explained in section 2.2 of
523
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
524
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
525
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
526
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
527
+ micro-conditioning as explained in section 2.2 of
528
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
529
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
530
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
531
+ To negatively condition the generation process based on a target image resolution. It should be as same
532
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
533
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
534
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
535
+ clip_skip (`int`, *optional*):
536
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
537
+ the output of the pre-final layer will be used for computing the prompt embeddings.
538
+ callback_on_step_end (`Callable`, *optional*):
539
+ A function that calls at the end of each denoising steps during the inference. The function is called
540
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
541
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
542
+ `callback_on_step_end_tensor_inputs`.
543
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
544
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
545
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
546
+ `._callback_tensor_inputs` attribute of your pipeine class.
547
+
548
+ Examples:
549
+
550
+ Returns:
551
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
552
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
553
+ otherwise a `tuple` is returned containing the output images.
554
+ """
555
+
556
+ callback = kwargs.pop("callback", None)
557
+ callback_steps = kwargs.pop("callback_steps", None)
558
+
559
+ if callback is not None:
560
+ deprecate(
561
+ "callback",
562
+ "1.0.0",
563
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
564
+ )
565
+ if callback_steps is not None:
566
+ deprecate(
567
+ "callback_steps",
568
+ "1.0.0",
569
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
570
+ )
571
+
572
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
573
+
574
+ # align format for control guidance
575
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
576
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
577
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
578
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
579
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
580
+ mult = len(controlnet.nets) if isinstance(controlnet, RBLNMultiControlNetModel) else 1
581
+ control_guidance_start, control_guidance_end = (
582
+ mult * [control_guidance_start],
583
+ mult * [control_guidance_end],
584
+ )
585
+
586
+ # 1. Check inputs. Raise error if not correct
587
+ self.check_inputs(
588
+ prompt,
589
+ prompt_2,
590
+ image,
591
+ callback_steps,
592
+ negative_prompt,
593
+ negative_prompt_2,
594
+ prompt_embeds,
595
+ negative_prompt_embeds,
596
+ pooled_prompt_embeds,
597
+ ip_adapter_image,
598
+ ip_adapter_image_embeds,
599
+ negative_pooled_prompt_embeds,
600
+ controlnet_conditioning_scale,
601
+ control_guidance_start,
602
+ control_guidance_end,
603
+ callback_on_step_end_tensor_inputs,
604
+ )
605
+
606
+ self._guidance_scale = guidance_scale
607
+ self._clip_skip = clip_skip
608
+ self._cross_attention_kwargs = cross_attention_kwargs
609
+ self._denoising_end = denoising_end
610
+
611
+ # 2. Define call parameters
612
+ if prompt is not None and isinstance(prompt, str):
613
+ batch_size = 1
614
+ elif prompt is not None and isinstance(prompt, list):
615
+ batch_size = len(prompt)
616
+ else:
617
+ batch_size = prompt_embeds.shape[0]
618
+
619
+ device = self._execution_device
620
+
621
+ if isinstance(controlnet, RBLNMultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
622
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
623
+
624
+ global_pool_conditions = (
625
+ controlnet.config.global_pool_conditions
626
+ if isinstance(controlnet, RBLNControlNetModel)
627
+ else controlnet.nets[0].config.global_pool_conditions
628
+ )
629
+ guess_mode = guess_mode or global_pool_conditions
630
+
631
+ # 3.1 Encode input prompt
632
+ text_encoder_lora_scale = (
633
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
634
+ )
635
+ (
636
+ prompt_embeds,
637
+ negative_prompt_embeds,
638
+ pooled_prompt_embeds,
639
+ negative_pooled_prompt_embeds,
640
+ ) = self.encode_prompt(
641
+ prompt,
642
+ prompt_2,
643
+ device,
644
+ num_images_per_prompt,
645
+ self.do_classifier_free_guidance,
646
+ negative_prompt,
647
+ negative_prompt_2,
648
+ prompt_embeds=prompt_embeds,
649
+ negative_prompt_embeds=negative_prompt_embeds,
650
+ pooled_prompt_embeds=pooled_prompt_embeds,
651
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
652
+ lora_scale=text_encoder_lora_scale,
653
+ clip_skip=self.clip_skip,
654
+ )
655
+
656
+ # 3.2 Encode ip_adapter_image
657
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
658
+ image_embeds = self.prepare_ip_adapter_image_embeds(
659
+ ip_adapter_image,
660
+ ip_adapter_image_embeds,
661
+ device,
662
+ batch_size * num_images_per_prompt,
663
+ self.do_classifier_free_guidance,
664
+ )
665
+
666
+ # 4. Prepare image
667
+ if isinstance(controlnet, RBLNControlNetModel):
668
+ image = self.prepare_image(
669
+ image=image,
670
+ width=width,
671
+ height=height,
672
+ batch_size=batch_size * num_images_per_prompt,
673
+ num_images_per_prompt=num_images_per_prompt,
674
+ device=device,
675
+ dtype=controlnet.dtype,
676
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
677
+ guess_mode=guess_mode,
678
+ )
679
+ height, width = image.shape[-2:]
680
+ elif isinstance(controlnet, RBLNMultiControlNetModel):
681
+ images = []
682
+
683
+ for image_ in image:
684
+ image_ = self.prepare_image(
685
+ image=image_,
686
+ width=width,
687
+ height=height,
688
+ batch_size=batch_size * num_images_per_prompt,
689
+ num_images_per_prompt=num_images_per_prompt,
690
+ device=device,
691
+ dtype=controlnet.dtype,
692
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
693
+ guess_mode=guess_mode,
694
+ )
695
+
696
+ images.append(image_)
697
+
698
+ image = images
699
+ height, width = image[0].shape[-2:]
700
+ else:
701
+ assert False
702
+
703
+ # 5. Prepare timesteps
704
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
705
+ timesteps = self.scheduler.timesteps
706
+ self._num_timesteps = len(timesteps)
707
+
708
+ # 6. Prepare latent variables
709
+ num_channels_latents = self.unet.config.in_channels
710
+ latents = self.prepare_latents(
711
+ batch_size * num_images_per_prompt,
712
+ num_channels_latents,
713
+ height,
714
+ width,
715
+ prompt_embeds.dtype,
716
+ device,
717
+ generator,
718
+ latents,
719
+ )
720
+
721
+ # 6.5 Optionally get Guidance Scale Embedding
722
+ timestep_cond = None
723
+ if self.unet.config.time_cond_proj_dim is not None:
724
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
725
+ timestep_cond = self.get_guidance_scale_embedding(
726
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
727
+ ).to(device=device, dtype=latents.dtype)
728
+
729
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
730
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
731
+
732
+ # 7.1 Create tensor stating which controlnets to keep
733
+ controlnet_keep = []
734
+ for i in range(len(timesteps)):
735
+ keeps = [
736
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
737
+ for s, e in zip(control_guidance_start, control_guidance_end)
738
+ ]
739
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, RBLNControlNetModel) else keeps)
740
+
741
+ # 7.2 Prepare added time ids & embeddings
742
+ if isinstance(image, list):
743
+ original_size = original_size or image[0].shape[-2:]
744
+ else:
745
+ original_size = original_size or image.shape[-2:]
746
+ target_size = target_size or (height, width)
747
+
748
+ add_text_embeds = pooled_prompt_embeds
749
+ if self.text_encoder_2 is None:
750
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
751
+ else:
752
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
753
+
754
+ add_time_ids = self._get_add_time_ids(
755
+ original_size,
756
+ crops_coords_top_left,
757
+ target_size,
758
+ dtype=prompt_embeds.dtype,
759
+ text_encoder_projection_dim=text_encoder_projection_dim,
760
+ )
761
+
762
+ if negative_original_size is not None and negative_target_size is not None:
763
+ negative_add_time_ids = self._get_add_time_ids(
764
+ negative_original_size,
765
+ negative_crops_coords_top_left,
766
+ negative_target_size,
767
+ dtype=prompt_embeds.dtype,
768
+ text_encoder_projection_dim=text_encoder_projection_dim,
769
+ )
770
+ else:
771
+ negative_add_time_ids = add_time_ids
772
+
773
+ if self.do_classifier_free_guidance:
774
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
775
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
776
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
777
+
778
+ prompt_embeds = prompt_embeds.to(device)
779
+ add_text_embeds = add_text_embeds.to(device)
780
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
781
+
782
+ # 8. Denoising loop
783
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
784
+
785
+ # 8.1 Apply denoising_end
786
+ if (
787
+ self.denoising_end is not None
788
+ and isinstance(self.denoising_end, float)
789
+ and self.denoising_end > 0
790
+ and self.denoising_end < 1
791
+ ):
792
+ discrete_timestep_cutoff = int(
793
+ round(
794
+ self.scheduler.config.num_train_timesteps
795
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
796
+ )
797
+ )
798
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
799
+ timesteps = timesteps[:num_inference_steps]
800
+
801
+ is_unet_compiled = is_compiled_module(self.unet)
802
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
803
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
804
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
805
+ for i, t in enumerate(timesteps):
806
+ # Relevant thread:
807
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
808
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
809
+ torch._inductor.cudagraph_mark_step_begin()
810
+ # expand the latents if we are doing classifier free guidance
811
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
812
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
813
+
814
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
815
+
816
+ # controlnet(s) inference
817
+ if guess_mode and self.do_classifier_free_guidance:
818
+ # Infer ControlNet only for the conditional batch.
819
+ control_model_input = latents
820
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
821
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
822
+ controlnet_added_cond_kwargs = {
823
+ "text_embeds": add_text_embeds.chunk(2)[1],
824
+ "time_ids": add_time_ids.chunk(2)[1],
825
+ }
826
+ else:
827
+ control_model_input = latent_model_input
828
+ controlnet_prompt_embeds = prompt_embeds
829
+ controlnet_added_cond_kwargs = added_cond_kwargs
830
+
831
+ if isinstance(controlnet_keep[i], list):
832
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
833
+ else:
834
+ controlnet_cond_scale = controlnet_conditioning_scale
835
+ if isinstance(controlnet_cond_scale, list):
836
+ controlnet_cond_scale = controlnet_cond_scale[0]
837
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
838
+
839
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
840
+ control_model_input,
841
+ t,
842
+ encoder_hidden_states=controlnet_prompt_embeds,
843
+ controlnet_cond=image,
844
+ conditioning_scale=cond_scale,
845
+ guess_mode=guess_mode,
846
+ added_cond_kwargs=controlnet_added_cond_kwargs,
847
+ return_dict=False,
848
+ )
849
+
850
+ if guess_mode and self.do_classifier_free_guidance:
851
+ # Infered ControlNet only for the conditional batch.
852
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
853
+ # add 0 to the unconditional batch to keep it unchanged.
854
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
855
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
856
+
857
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
858
+ added_cond_kwargs["image_embeds"] = image_embeds
859
+
860
+ # predict the noise residual
861
+ noise_pred = self.unet(
862
+ latent_model_input,
863
+ t,
864
+ encoder_hidden_states=prompt_embeds,
865
+ timestep_cond=timestep_cond,
866
+ cross_attention_kwargs=self.cross_attention_kwargs,
867
+ down_block_additional_residuals=down_block_res_samples,
868
+ mid_block_additional_residual=mid_block_res_sample,
869
+ added_cond_kwargs=added_cond_kwargs,
870
+ return_dict=False,
871
+ )[0]
872
+
873
+ # perform guidance
874
+ if self.do_classifier_free_guidance:
875
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
876
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
877
+
878
+ # compute the previous noisy sample x_t -> x_t-1
879
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
880
+
881
+ if callback_on_step_end is not None:
882
+ callback_kwargs = {}
883
+ for k in callback_on_step_end_tensor_inputs:
884
+ callback_kwargs[k] = locals()[k]
885
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
886
+
887
+ latents = callback_outputs.pop("latents", latents)
888
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
889
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
890
+
891
+ # call the callback, if provided
892
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
893
+ progress_bar.update()
894
+ if callback is not None and i % callback_steps == 0:
895
+ step_idx = i // getattr(self.scheduler, "order", 1)
896
+ callback(step_idx, t, latents)
897
+
898
+ if not output_type == "latent":
899
+ # make sure the VAE is in float32 mode, as it overflows in float16
900
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
901
+
902
+ if needs_upcasting:
903
+ self.upcast_vae()
904
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
905
+
906
+ # unscale/denormalize the latents
907
+ # denormalize with the mean and std if available and not None
908
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
909
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
910
+ if has_latents_mean and has_latents_std:
911
+ latents_mean = (
912
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
913
+ )
914
+ latents_std = (
915
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
916
+ )
917
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
918
+ else:
919
+ latents = latents / self.vae.config.scaling_factor
920
+
921
+ image = self.vae.decode(latents, return_dict=False)[0]
922
+
923
+ # cast back to fp16 if needed
924
+ if needs_upcasting:
925
+ self.vae.to(dtype=torch.float16)
926
+ else:
927
+ image = latents
928
+
929
+ if not output_type == "latent":
930
+ # apply watermark if available
931
+ if self.watermark is not None:
932
+ image = self.watermark.apply_watermark(image)
933
+
934
+ image = self.image_processor.postprocess(image, output_type=output_type)
935
+
936
+ # Offload all models
937
+ self.maybe_free_model_hooks()
938
+
939
+ if not return_dict:
940
+ return (image,)
941
+
942
+ return StableDiffusionXLPipelineOutput(images=image)