optimum-rbln 0.1.0__py3-none-any.whl → 0.1.4__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 (41) hide show
  1. optimum/rbln/__init__.py +8 -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 +39 -6
  19. optimum/rbln/modeling_seq2seq.py +19 -4
  20. optimum/rbln/transformers/__init__.py +2 -0
  21. optimum/rbln/transformers/generation/__init__.py +1 -0
  22. optimum/rbln/transformers/generation/streamers.py +17 -0
  23. optimum/rbln/transformers/generation/utils.py +399 -0
  24. optimum/rbln/transformers/models/__init__.py +1 -0
  25. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +24 -333
  26. optimum/rbln/transformers/models/llama/llama_architecture.py +49 -17
  27. optimum/rbln/transformers/models/llama/llama_architecture_cb.py +759 -0
  28. optimum/rbln/transformers/models/llama/modeling_llama.py +187 -75
  29. optimum/rbln/transformers/models/midm/__init__.py +32 -0
  30. optimum/rbln/transformers/models/midm/hf_hub_cached/configuration_midm.py +22 -0
  31. optimum/rbln/transformers/models/midm/hf_hub_cached/midm_bitext_tokenization.py +303 -0
  32. optimum/rbln/transformers/models/midm/hf_hub_cached/modeling_midm.py +1473 -0
  33. optimum/rbln/transformers/models/midm/hf_hub_cached/rotary_position_embedding.py +98 -0
  34. optimum/rbln/transformers/models/midm/midm_architecture.py +506 -0
  35. optimum/rbln/transformers/models/midm/modeling_midm.py +426 -0
  36. optimum/rbln/transformers/models/whisper/modeling_whisper.py +13 -3
  37. {optimum_rbln-0.1.0.dist-info → optimum_rbln-0.1.4.dist-info}/METADATA +5 -4
  38. optimum_rbln-0.1.4.dist-info/RECORD +63 -0
  39. {optimum_rbln-0.1.0.dist-info → optimum_rbln-0.1.4.dist-info}/WHEEL +1 -1
  40. optimum_rbln-0.1.0.dist-info/RECORD +0 -51
  41. {optimum_rbln-0.1.0.dist-info → optimum_rbln-0.1.4.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,955 @@
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 StableDiffusionXLControlNetImg2ImgPipeline
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
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 RBLNStableDiffusionXLControlNetImg2ImgPipeline(StableDiffusionXLControlNetImg2ImgPipeline):
47
+ @classmethod
48
+ def from_pretrained(cls, model_id, **kwargs):
49
+ """
50
+ Pipeline for image-to-image generation using Stable Diffusion XL with ControlNet.
51
+
52
+ This model inherits from [`StableDiffusionXLControlNetImg2ImgPipeline`]. 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 RBLNStableDiffusionXLControlNetImg2Img 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
+ vae.model[1],
175
+ unet.model[0],
176
+ text_encoder.model[0],
177
+ text_encoder_2.model[0],
178
+ controlnet.model[0],
179
+ ]
180
+
181
+ return model
182
+
183
+ def check_inputs(
184
+ self,
185
+ prompt,
186
+ prompt_2,
187
+ image,
188
+ strength,
189
+ num_inference_steps,
190
+ callback_steps,
191
+ negative_prompt=None,
192
+ negative_prompt_2=None,
193
+ prompt_embeds=None,
194
+ negative_prompt_embeds=None,
195
+ pooled_prompt_embeds=None,
196
+ negative_pooled_prompt_embeds=None,
197
+ ip_adapter_image=None,
198
+ ip_adapter_image_embeds=None,
199
+ controlnet_conditioning_scale=1.0,
200
+ control_guidance_start=0.0,
201
+ control_guidance_end=1.0,
202
+ callback_on_step_end_tensor_inputs=None,
203
+ ):
204
+ if strength < 0 or strength > 1:
205
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
206
+ if num_inference_steps is None:
207
+ raise ValueError("`num_inference_steps` cannot be None.")
208
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
209
+ raise ValueError(
210
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
211
+ f" {type(num_inference_steps)}."
212
+ )
213
+
214
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
215
+ raise ValueError(
216
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
217
+ f" {type(callback_steps)}."
218
+ )
219
+
220
+ if callback_on_step_end_tensor_inputs is not None and not all(
221
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
222
+ ):
223
+ raise ValueError(
224
+ 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]}"
225
+ )
226
+
227
+ if prompt is not None and prompt_embeds is not None:
228
+ raise ValueError(
229
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
230
+ " only forward one of the two."
231
+ )
232
+ elif prompt_2 is not None and prompt_embeds is not None:
233
+ raise ValueError(
234
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
235
+ " only forward one of the two."
236
+ )
237
+ elif prompt is None and prompt_embeds is None:
238
+ raise ValueError(
239
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
240
+ )
241
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
242
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
243
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
244
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
245
+
246
+ if negative_prompt is not None and negative_prompt_embeds is not None:
247
+ raise ValueError(
248
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
249
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
250
+ )
251
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
252
+ raise ValueError(
253
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
254
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
255
+ )
256
+
257
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
258
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
259
+ raise ValueError(
260
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
261
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
262
+ f" {negative_prompt_embeds.shape}."
263
+ )
264
+
265
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
266
+ raise ValueError(
267
+ "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`."
268
+ )
269
+
270
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
271
+ raise ValueError(
272
+ "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`."
273
+ )
274
+
275
+ # `prompt` needs more sophisticated handling when there are multiple
276
+ # conditionings.
277
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
278
+ if isinstance(prompt, list):
279
+ logger.warning(
280
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
281
+ " prompts. The conditionings will be fixed across the prompts."
282
+ )
283
+
284
+ # Check `image`
285
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
286
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
287
+ )
288
+ if (
289
+ isinstance(self.controlnet, RBLNControlNetModel)
290
+ or is_compiled
291
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
292
+ ):
293
+ self.check_image(image, prompt, prompt_embeds)
294
+ elif (
295
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
296
+ or is_compiled
297
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
298
+ ):
299
+ if not isinstance(image, list):
300
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
301
+
302
+ # When `image` is a nested list:
303
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
304
+ elif any(isinstance(i, list) for i in image):
305
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
306
+ elif len(image) != len(self.controlnet.nets):
307
+ raise ValueError(
308
+ 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."
309
+ )
310
+
311
+ for image_ in image:
312
+ self.check_image(image_, prompt, prompt_embeds)
313
+ else:
314
+ assert False
315
+
316
+ # Check `controlnet_conditioning_scale`
317
+ if (
318
+ isinstance(self.controlnet, RBLNControlNetModel)
319
+ or is_compiled
320
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
321
+ ):
322
+ if not isinstance(controlnet_conditioning_scale, float):
323
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
324
+ elif (
325
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
326
+ or is_compiled
327
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
328
+ ):
329
+ if isinstance(controlnet_conditioning_scale, list):
330
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
331
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
332
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
333
+ self.controlnet.nets
334
+ ):
335
+ raise ValueError(
336
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
337
+ " the same length as the number of controlnets"
338
+ )
339
+ else:
340
+ assert False
341
+
342
+ if not isinstance(control_guidance_start, (tuple, list)):
343
+ control_guidance_start = [control_guidance_start]
344
+
345
+ if not isinstance(control_guidance_end, (tuple, list)):
346
+ control_guidance_end = [control_guidance_end]
347
+
348
+ if len(control_guidance_start) != len(control_guidance_end):
349
+ raise ValueError(
350
+ 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."
351
+ )
352
+
353
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
354
+ if len(control_guidance_start) != len(self.controlnet.nets):
355
+ raise ValueError(
356
+ 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)}."
357
+ )
358
+
359
+ for start, end in zip(control_guidance_start, control_guidance_end):
360
+ if start >= end:
361
+ raise ValueError(
362
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
363
+ )
364
+ if start < 0.0:
365
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
366
+ if end > 1.0:
367
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
368
+
369
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
370
+ raise ValueError(
371
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
372
+ )
373
+
374
+ if ip_adapter_image_embeds is not None:
375
+ if not isinstance(ip_adapter_image_embeds, list):
376
+ raise ValueError(
377
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
378
+ )
379
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
380
+ raise ValueError(
381
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
382
+ )
383
+
384
+ @torch.no_grad()
385
+ def __call__(
386
+ self,
387
+ prompt: Union[str, List[str]] = None,
388
+ prompt_2: Optional[Union[str, List[str]]] = None,
389
+ image: PipelineImageInput = None,
390
+ control_image: PipelineImageInput = None,
391
+ height: Optional[int] = None,
392
+ width: Optional[int] = None,
393
+ strength: float = 0.8,
394
+ num_inference_steps: int = 50,
395
+ guidance_scale: float = 5.0,
396
+ negative_prompt: Optional[Union[str, List[str]]] = None,
397
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
398
+ num_images_per_prompt: Optional[int] = 1,
399
+ eta: float = 0.0,
400
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
401
+ latents: Optional[torch.FloatTensor] = None,
402
+ prompt_embeds: Optional[torch.FloatTensor] = None,
403
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
404
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
405
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
406
+ ip_adapter_image: Optional[PipelineImageInput] = None,
407
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
408
+ output_type: Optional[str] = "pil",
409
+ return_dict: bool = True,
410
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
411
+ controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
412
+ guess_mode: bool = False,
413
+ control_guidance_start: Union[float, List[float]] = 0.0,
414
+ control_guidance_end: Union[float, List[float]] = 1.0,
415
+ original_size: Tuple[int, int] = None,
416
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
417
+ target_size: Tuple[int, int] = None,
418
+ negative_original_size: Optional[Tuple[int, int]] = None,
419
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
420
+ negative_target_size: Optional[Tuple[int, int]] = None,
421
+ aesthetic_score: float = 6.0,
422
+ negative_aesthetic_score: float = 2.5,
423
+ clip_skip: Optional[int] = None,
424
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
425
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
426
+ **kwargs,
427
+ ):
428
+ r"""
429
+ Function invoked when calling the pipeline for generation.
430
+
431
+ Args:
432
+ prompt (`str` or `List[str]`, *optional*):
433
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
434
+ instead.
435
+ prompt_2 (`str` or `List[str]`, *optional*):
436
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
437
+ used in both text-encoders
438
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
439
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
440
+ The initial image will be used as the starting point for the image generation process. Can also accept
441
+ image latents as `image`, if passing latents directly, it will not be encoded again.
442
+ control_image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
443
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
444
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
445
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can
446
+ also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If
447
+ height and/or width are passed, `image` is resized according to them. If multiple ControlNets are
448
+ specified in init, images must be passed as a list such that each element of the list can be correctly
449
+ batched for input to a single controlnet.
450
+ height (`int`, *optional*, defaults to the size of control_image):
451
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
452
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
453
+ and checkpoints that are not specifically fine-tuned on low resolutions.
454
+ width (`int`, *optional*, defaults to the size of control_image):
455
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
456
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
457
+ and checkpoints that are not specifically fine-tuned on low resolutions.
458
+ strength (`float`, *optional*, defaults to 0.8):
459
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
460
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
461
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
462
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
463
+ essentially ignores `image`.
464
+ num_inference_steps (`int`, *optional*, defaults to 50):
465
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
466
+ expense of slower inference.
467
+ guidance_scale (`float`, *optional*, defaults to 7.5):
468
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
469
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
470
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
471
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
472
+ usually at the expense of lower image quality.
473
+ negative_prompt (`str` or `List[str]`, *optional*):
474
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
475
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
476
+ less than `1`).
477
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
478
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
479
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
480
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
481
+ The number of images to generate per prompt.
482
+ eta (`float`, *optional*, defaults to 0.0):
483
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
484
+ [`schedulers.DDIMScheduler`], will be ignored for others.
485
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
486
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
487
+ to make generation deterministic.
488
+ latents (`torch.FloatTensor`, *optional*):
489
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
490
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
491
+ tensor will ge generated by sampling using the supplied random `generator`.
492
+ prompt_embeds (`torch.FloatTensor`, *optional*):
493
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
494
+ provided, text embeddings will be generated from `prompt` input argument.
495
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
496
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
497
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
498
+ argument.
499
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
500
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
501
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
502
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
503
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
504
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
505
+ input argument.
506
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
507
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
508
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
509
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
510
+ if `do_classifier_free_guidance` is set to `True`.
511
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
512
+ output_type (`str`, *optional*, defaults to `"pil"`):
513
+ The output format of the generate image. Choose between
514
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
515
+ return_dict (`bool`, *optional*, defaults to `True`):
516
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
517
+ plain tuple.
518
+ cross_attention_kwargs (`dict`, *optional*):
519
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
520
+ `self.processor` in
521
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
522
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
523
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
524
+ to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
525
+ corresponding scale as a list.
526
+ guess_mode (`bool`, *optional*, defaults to `False`):
527
+ In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
528
+ you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
529
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
530
+ The percentage of total steps at which the controlnet starts applying.
531
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
532
+ The percentage of total steps at which the controlnet stops applying.
533
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
534
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
535
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
536
+ explained in section 2.2 of
537
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
538
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
539
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
540
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
541
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
542
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
543
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
544
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
545
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
546
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
547
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
548
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
549
+ micro-conditioning as explained in section 2.2 of
550
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
551
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
552
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
553
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
554
+ micro-conditioning as explained in section 2.2 of
555
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
556
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
557
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
558
+ To negatively condition the generation process based on a target image resolution. It should be as same
559
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
560
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
561
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
562
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
563
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
564
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
565
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
566
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
567
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
568
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
569
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
570
+ clip_skip (`int`, *optional*):
571
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
572
+ the output of the pre-final layer will be used for computing the prompt embeddings.
573
+ callback_on_step_end (`Callable`, *optional*):
574
+ A function that calls at the end of each denoising steps during the inference. The function is called
575
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
576
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
577
+ `callback_on_step_end_tensor_inputs`.
578
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
579
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
580
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
581
+ `._callback_tensor_inputs` attribute of your pipeine class.
582
+
583
+ Examples:
584
+
585
+ Returns:
586
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
587
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple`
588
+ containing the output images.
589
+ """
590
+
591
+ callback = kwargs.pop("callback", None)
592
+ callback_steps = kwargs.pop("callback_steps", None)
593
+
594
+ if callback is not None:
595
+ deprecate(
596
+ "callback",
597
+ "1.0.0",
598
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
599
+ )
600
+ if callback_steps is not None:
601
+ deprecate(
602
+ "callback_steps",
603
+ "1.0.0",
604
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
605
+ )
606
+
607
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
608
+
609
+ # align format for control guidance
610
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
611
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
612
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
613
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
614
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
615
+ mult = len(controlnet.nets) if isinstance(controlnet, RBLNMultiControlNetModel) else 1
616
+ control_guidance_start, control_guidance_end = (
617
+ mult * [control_guidance_start],
618
+ mult * [control_guidance_end],
619
+ )
620
+
621
+ # 1. Check inputs. Raise error if not correct
622
+ self.check_inputs(
623
+ prompt,
624
+ prompt_2,
625
+ control_image,
626
+ strength,
627
+ num_inference_steps,
628
+ callback_steps,
629
+ negative_prompt,
630
+ negative_prompt_2,
631
+ prompt_embeds,
632
+ negative_prompt_embeds,
633
+ pooled_prompt_embeds,
634
+ negative_pooled_prompt_embeds,
635
+ ip_adapter_image,
636
+ ip_adapter_image_embeds,
637
+ controlnet_conditioning_scale,
638
+ control_guidance_start,
639
+ control_guidance_end,
640
+ callback_on_step_end_tensor_inputs,
641
+ )
642
+
643
+ self._guidance_scale = guidance_scale
644
+ self._clip_skip = clip_skip
645
+ self._cross_attention_kwargs = cross_attention_kwargs
646
+
647
+ # 2. Define call parameters
648
+ if prompt is not None and isinstance(prompt, str):
649
+ batch_size = 1
650
+ elif prompt is not None and isinstance(prompt, list):
651
+ batch_size = len(prompt)
652
+ else:
653
+ batch_size = prompt_embeds.shape[0]
654
+
655
+ device = self._execution_device
656
+
657
+ if isinstance(controlnet, RBLNMultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
658
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
659
+
660
+ global_pool_conditions = (
661
+ controlnet.config.global_pool_conditions
662
+ if isinstance(controlnet, RBLNControlNetModel)
663
+ else controlnet.nets[0].config.global_pool_conditions
664
+ )
665
+ guess_mode = guess_mode or global_pool_conditions
666
+
667
+ # 3.1. Encode input prompt
668
+ text_encoder_lora_scale = (
669
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
670
+ )
671
+ (
672
+ prompt_embeds,
673
+ negative_prompt_embeds,
674
+ pooled_prompt_embeds,
675
+ negative_pooled_prompt_embeds,
676
+ ) = self.encode_prompt(
677
+ prompt,
678
+ prompt_2,
679
+ device,
680
+ num_images_per_prompt,
681
+ self.do_classifier_free_guidance,
682
+ negative_prompt,
683
+ negative_prompt_2,
684
+ prompt_embeds=prompt_embeds,
685
+ negative_prompt_embeds=negative_prompt_embeds,
686
+ pooled_prompt_embeds=pooled_prompt_embeds,
687
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
688
+ lora_scale=text_encoder_lora_scale,
689
+ clip_skip=self.clip_skip,
690
+ )
691
+
692
+ # 3.2 Encode ip_adapter_image
693
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
694
+ image_embeds = self.prepare_ip_adapter_image_embeds(
695
+ ip_adapter_image,
696
+ ip_adapter_image_embeds,
697
+ device,
698
+ batch_size * num_images_per_prompt,
699
+ self.do_classifier_free_guidance,
700
+ )
701
+
702
+ # 4. Prepare image and controlnet_conditioning_image
703
+ image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
704
+
705
+ if isinstance(controlnet, RBLNControlNetModel):
706
+ control_image = self.prepare_control_image(
707
+ image=control_image,
708
+ width=width,
709
+ height=height,
710
+ batch_size=batch_size * num_images_per_prompt,
711
+ num_images_per_prompt=num_images_per_prompt,
712
+ device=device,
713
+ dtype=controlnet.dtype,
714
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
715
+ guess_mode=guess_mode,
716
+ )
717
+ height, width = control_image.shape[-2:]
718
+ elif isinstance(controlnet, RBLNMultiControlNetModel):
719
+ control_images = []
720
+
721
+ for control_image_ in control_image:
722
+ control_image_ = self.prepare_control_image(
723
+ image=control_image_,
724
+ width=width,
725
+ height=height,
726
+ batch_size=batch_size * num_images_per_prompt,
727
+ num_images_per_prompt=num_images_per_prompt,
728
+ device=device,
729
+ dtype=controlnet.dtype,
730
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
731
+ guess_mode=guess_mode,
732
+ )
733
+
734
+ control_images.append(control_image_)
735
+
736
+ control_image = control_images
737
+ height, width = control_image[0].shape[-2:]
738
+ else:
739
+ assert False
740
+
741
+ # 5. Prepare timesteps
742
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
743
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
744
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
745
+ self._num_timesteps = len(timesteps)
746
+
747
+ # 6. Prepare latent variables
748
+ latents = self.prepare_latents(
749
+ image,
750
+ latent_timestep,
751
+ batch_size,
752
+ num_images_per_prompt,
753
+ prompt_embeds.dtype,
754
+ device,
755
+ generator,
756
+ True,
757
+ )
758
+
759
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
760
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
761
+
762
+ # 7.1 Create tensor stating which controlnets to keep
763
+ controlnet_keep = []
764
+ for i in range(len(timesteps)):
765
+ keeps = [
766
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
767
+ for s, e in zip(control_guidance_start, control_guidance_end)
768
+ ]
769
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, RBLNControlNetModel) else keeps)
770
+
771
+ # 7.2 Prepare added time ids & embeddings
772
+ if isinstance(control_image, list):
773
+ original_size = original_size or control_image[0].shape[-2:]
774
+ else:
775
+ original_size = original_size or control_image.shape[-2:]
776
+ target_size = target_size or (height, width)
777
+
778
+ if negative_original_size is None:
779
+ negative_original_size = original_size
780
+ if negative_target_size is None:
781
+ negative_target_size = target_size
782
+ add_text_embeds = pooled_prompt_embeds
783
+
784
+ if self.text_encoder_2 is None:
785
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
786
+ else:
787
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
788
+
789
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
790
+ original_size,
791
+ crops_coords_top_left,
792
+ target_size,
793
+ aesthetic_score,
794
+ negative_aesthetic_score,
795
+ negative_original_size,
796
+ negative_crops_coords_top_left,
797
+ negative_target_size,
798
+ dtype=prompt_embeds.dtype,
799
+ text_encoder_projection_dim=text_encoder_projection_dim,
800
+ )
801
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
802
+
803
+ if self.do_classifier_free_guidance:
804
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
805
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
806
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
807
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
808
+
809
+ prompt_embeds = prompt_embeds.to(device)
810
+ add_text_embeds = add_text_embeds.to(device)
811
+ add_time_ids = add_time_ids.to(device)
812
+
813
+ # 8. Denoising loop
814
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
815
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
816
+ for i, t in enumerate(timesteps):
817
+ # expand the latents if we are doing classifier free guidance
818
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
819
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
820
+
821
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
822
+
823
+ # controlnet(s) inference
824
+ if guess_mode and self.do_classifier_free_guidance:
825
+ # Infer ControlNet only for the conditional batch.
826
+ control_model_input = latents
827
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
828
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
829
+ controlnet_added_cond_kwargs = {
830
+ "text_embeds": add_text_embeds.chunk(2)[1],
831
+ "time_ids": add_time_ids.chunk(2)[1],
832
+ }
833
+ else:
834
+ control_model_input = latent_model_input
835
+ controlnet_prompt_embeds = prompt_embeds
836
+ controlnet_added_cond_kwargs = added_cond_kwargs
837
+
838
+ if isinstance(controlnet_keep[i], list):
839
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
840
+ else:
841
+ controlnet_cond_scale = controlnet_conditioning_scale
842
+ if isinstance(controlnet_cond_scale, list):
843
+ controlnet_cond_scale = controlnet_cond_scale[0]
844
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
845
+
846
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
847
+ control_model_input,
848
+ t,
849
+ encoder_hidden_states=controlnet_prompt_embeds,
850
+ controlnet_cond=control_image,
851
+ conditioning_scale=cond_scale,
852
+ guess_mode=guess_mode,
853
+ added_cond_kwargs=controlnet_added_cond_kwargs,
854
+ return_dict=False,
855
+ )
856
+
857
+ if guess_mode and self.do_classifier_free_guidance:
858
+ # Infered ControlNet only for the conditional batch.
859
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
860
+ # add 0 to the unconditional batch to keep it unchanged.
861
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
862
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
863
+
864
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
865
+ added_cond_kwargs["image_embeds"] = image_embeds
866
+
867
+ # predict the noise residual
868
+ noise_pred = self.unet(
869
+ latent_model_input,
870
+ t,
871
+ encoder_hidden_states=prompt_embeds,
872
+ cross_attention_kwargs=self.cross_attention_kwargs,
873
+ down_block_additional_residuals=down_block_res_samples,
874
+ mid_block_additional_residual=mid_block_res_sample,
875
+ added_cond_kwargs=added_cond_kwargs,
876
+ return_dict=False,
877
+ )[0]
878
+
879
+ # perform guidance
880
+ if self.do_classifier_free_guidance:
881
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
882
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
883
+
884
+ # compute the previous noisy sample x_t -> x_t-1
885
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
886
+
887
+ if callback_on_step_end is not None:
888
+ callback_kwargs = {}
889
+ for k in callback_on_step_end_tensor_inputs:
890
+ callback_kwargs[k] = locals()[k]
891
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
892
+
893
+ latents = callback_outputs.pop("latents", latents)
894
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
895
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
896
+
897
+ # call the callback, if provided
898
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
899
+ progress_bar.update()
900
+ if callback is not None and i % callback_steps == 0:
901
+ step_idx = i // getattr(self.scheduler, "order", 1)
902
+ callback(step_idx, t, latents)
903
+
904
+ # If we do sequential model offloading, let's offload unet and controlnet
905
+ # manually for max memory savings
906
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
907
+ self.unet.to("cpu")
908
+ self.controlnet.to("cpu")
909
+ torch.cuda.empty_cache()
910
+
911
+ if not output_type == "latent":
912
+ # make sure the VAE is in float32 mode, as it overflows in float16
913
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
914
+
915
+ if needs_upcasting:
916
+ self.upcast_vae()
917
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
918
+
919
+ # unscale/denormalize the latents
920
+ # denormalize with the mean and std if available and not None
921
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
922
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
923
+ if has_latents_mean and has_latents_std:
924
+ latents_mean = (
925
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
926
+ )
927
+ latents_std = (
928
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
929
+ )
930
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
931
+ else:
932
+ latents = latents / self.vae.config.scaling_factor
933
+
934
+ image = self.vae.decode(latents, return_dict=False)[0]
935
+
936
+ # cast back to fp16 if needed
937
+ if needs_upcasting:
938
+ self.vae.to(dtype=torch.float16)
939
+ else:
940
+ image = latents
941
+ return StableDiffusionXLPipelineOutput(images=image)
942
+
943
+ # apply watermark if available
944
+ if self.watermark is not None:
945
+ image = self.watermark.apply_watermark(image)
946
+
947
+ image = self.image_processor.postprocess(image, output_type=output_type)
948
+
949
+ # Offload all models
950
+ self.maybe_free_model_hooks()
951
+
952
+ if not return_dict:
953
+ return (image,)
954
+
955
+ return StableDiffusionXLPipelineOutput(images=image)