diffusers 0.17.1__py3-none-any.whl → 0.18.2__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (120) hide show
  1. diffusers/__init__.py +26 -1
  2. diffusers/configuration_utils.py +34 -29
  3. diffusers/dependency_versions_table.py +4 -0
  4. diffusers/image_processor.py +125 -12
  5. diffusers/loaders.py +169 -203
  6. diffusers/models/attention.py +24 -1
  7. diffusers/models/attention_flax.py +10 -5
  8. diffusers/models/attention_processor.py +3 -0
  9. diffusers/models/autoencoder_kl.py +114 -33
  10. diffusers/models/controlnet.py +131 -14
  11. diffusers/models/controlnet_flax.py +37 -26
  12. diffusers/models/cross_attention.py +17 -17
  13. diffusers/models/embeddings.py +67 -0
  14. diffusers/models/modeling_flax_utils.py +64 -56
  15. diffusers/models/modeling_utils.py +193 -104
  16. diffusers/models/prior_transformer.py +207 -37
  17. diffusers/models/resnet.py +26 -26
  18. diffusers/models/transformer_2d.py +36 -41
  19. diffusers/models/transformer_temporal.py +24 -21
  20. diffusers/models/unet_1d.py +31 -25
  21. diffusers/models/unet_2d.py +43 -30
  22. diffusers/models/unet_2d_blocks.py +210 -89
  23. diffusers/models/unet_2d_blocks_flax.py +12 -12
  24. diffusers/models/unet_2d_condition.py +172 -64
  25. diffusers/models/unet_2d_condition_flax.py +38 -24
  26. diffusers/models/unet_3d_blocks.py +34 -31
  27. diffusers/models/unet_3d_condition.py +101 -34
  28. diffusers/models/vae.py +5 -5
  29. diffusers/models/vae_flax.py +37 -34
  30. diffusers/models/vq_model.py +23 -14
  31. diffusers/pipelines/__init__.py +24 -1
  32. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +1 -1
  33. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -3
  34. diffusers/pipelines/consistency_models/__init__.py +1 -0
  35. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +337 -0
  36. diffusers/pipelines/controlnet/multicontrolnet.py +120 -1
  37. diffusers/pipelines/controlnet/pipeline_controlnet.py +59 -17
  38. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +60 -15
  39. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +60 -17
  40. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
  41. diffusers/pipelines/kandinsky/__init__.py +1 -1
  42. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +4 -6
  43. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +1 -0
  44. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +1 -0
  45. diffusers/pipelines/kandinsky2_2/__init__.py +7 -0
  46. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +317 -0
  47. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +372 -0
  48. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +434 -0
  49. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +398 -0
  50. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +531 -0
  51. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +541 -0
  52. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +605 -0
  53. diffusers/pipelines/pipeline_flax_utils.py +2 -2
  54. diffusers/pipelines/pipeline_utils.py +124 -146
  55. diffusers/pipelines/shap_e/__init__.py +27 -0
  56. diffusers/pipelines/shap_e/camera.py +147 -0
  57. diffusers/pipelines/shap_e/pipeline_shap_e.py +390 -0
  58. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +349 -0
  59. diffusers/pipelines/shap_e/renderer.py +709 -0
  60. diffusers/pipelines/stable_diffusion/__init__.py +2 -0
  61. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +261 -66
  62. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +3 -3
  63. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -3
  64. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +4 -2
  65. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  66. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +1 -1
  67. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  68. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +719 -0
  69. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -1
  70. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +832 -0
  71. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +17 -7
  72. diffusers/pipelines/stable_diffusion_xl/__init__.py +26 -0
  73. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +823 -0
  74. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +896 -0
  75. diffusers/pipelines/stable_diffusion_xl/watermark.py +31 -0
  76. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -1
  77. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +5 -1
  78. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +771 -0
  79. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +92 -6
  80. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  81. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +209 -91
  82. diffusers/schedulers/__init__.py +3 -0
  83. diffusers/schedulers/scheduling_consistency_models.py +380 -0
  84. diffusers/schedulers/scheduling_ddim.py +28 -6
  85. diffusers/schedulers/scheduling_ddim_inverse.py +19 -4
  86. diffusers/schedulers/scheduling_ddim_parallel.py +642 -0
  87. diffusers/schedulers/scheduling_ddpm.py +53 -7
  88. diffusers/schedulers/scheduling_ddpm_parallel.py +604 -0
  89. diffusers/schedulers/scheduling_deis_multistep.py +66 -11
  90. diffusers/schedulers/scheduling_dpmsolver_multistep.py +55 -13
  91. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +19 -4
  92. diffusers/schedulers/scheduling_dpmsolver_sde.py +73 -11
  93. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +23 -7
  94. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +58 -9
  95. diffusers/schedulers/scheduling_euler_discrete.py +58 -8
  96. diffusers/schedulers/scheduling_heun_discrete.py +89 -14
  97. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +73 -11
  98. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +73 -11
  99. diffusers/schedulers/scheduling_lms_discrete.py +57 -8
  100. diffusers/schedulers/scheduling_pndm.py +46 -10
  101. diffusers/schedulers/scheduling_repaint.py +19 -4
  102. diffusers/schedulers/scheduling_sde_ve.py +5 -1
  103. diffusers/schedulers/scheduling_unclip.py +43 -4
  104. diffusers/schedulers/scheduling_unipc_multistep.py +48 -7
  105. diffusers/training_utils.py +1 -1
  106. diffusers/utils/__init__.py +2 -1
  107. diffusers/utils/dummy_pt_objects.py +60 -0
  108. diffusers/utils/dummy_torch_and_transformers_and_invisible_watermark_objects.py +32 -0
  109. diffusers/utils/dummy_torch_and_transformers_objects.py +180 -0
  110. diffusers/utils/hub_utils.py +1 -1
  111. diffusers/utils/import_utils.py +20 -3
  112. diffusers/utils/logging.py +15 -18
  113. diffusers/utils/outputs.py +3 -3
  114. diffusers/utils/testing_utils.py +15 -0
  115. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/METADATA +4 -2
  116. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/RECORD +120 -94
  117. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/WHEEL +1 -1
  118. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/LICENSE +0 -0
  119. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/entry_points.txt +0 -0
  120. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,823 @@
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
20
+
21
+ from ...image_processor import VaeImageProcessor
22
+ from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
23
+ from ...models import AutoencoderKL, UNet2DConditionModel
24
+ from ...models.attention_processor import (
25
+ AttnProcessor2_0,
26
+ LoRAAttnProcessor2_0,
27
+ LoRAXFormersAttnProcessor,
28
+ XFormersAttnProcessor,
29
+ )
30
+ from ...schedulers import KarrasDiffusionSchedulers
31
+ from ...utils import (
32
+ is_accelerate_available,
33
+ is_accelerate_version,
34
+ logging,
35
+ randn_tensor,
36
+ replace_example_docstring,
37
+ )
38
+ from ..pipeline_utils import DiffusionPipeline
39
+ from . import StableDiffusionXLPipelineOutput
40
+ from .watermark import StableDiffusionXLWatermarker
41
+
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+ EXAMPLE_DOC_STRING = """
46
+ Examples:
47
+ ```py
48
+ >>> import torch
49
+ >>> from diffusers import StableDiffusionXLPipeline
50
+
51
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
52
+ ... "stabilityai/stable-diffusion-xl-base-0.9", torch_dtype=torch.float16
53
+ ... )
54
+ >>> pipe = pipe.to("cuda")
55
+
56
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
57
+ >>> image = pipe(prompt).images[0]
58
+ ```
59
+ """
60
+
61
+
62
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
63
+ """
64
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
65
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
66
+ """
67
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
68
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
69
+ # rescale the results from guidance (fixes overexposure)
70
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
71
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
72
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
73
+ return noise_cfg
74
+
75
+
76
+ class StableDiffusionXLPipeline(DiffusionPipeline, FromSingleFileMixin):
77
+ r"""
78
+ Pipeline for text-to-image generation using Stable Diffusion.
79
+
80
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
81
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
82
+
83
+ In addition the pipeline inherits the following loading methods:
84
+ - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]
85
+ - *LoRA*: [`loaders.LoraLoaderMixin.load_lora_weights`]
86
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
87
+
88
+ as well as the following saving methods:
89
+ - *LoRA*: [`loaders.LoraLoaderMixin.save_lora_weights`]
90
+
91
+ Args:
92
+ vae ([`AutoencoderKL`]):
93
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
94
+ text_encoder ([`CLIPTextModel`]):
95
+ Frozen text-encoder. Stable Diffusion uses the text portion of
96
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
97
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
98
+ tokenizer (`CLIPTokenizer`):
99
+ Tokenizer of class
100
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
101
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
102
+ scheduler ([`SchedulerMixin`]):
103
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
104
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
105
+ """
106
+
107
+ def __init__(
108
+ self,
109
+ vae: AutoencoderKL,
110
+ text_encoder: CLIPTextModel,
111
+ text_encoder_2: CLIPTextModelWithProjection,
112
+ tokenizer: CLIPTokenizer,
113
+ tokenizer_2: CLIPTokenizer,
114
+ unet: UNet2DConditionModel,
115
+ scheduler: KarrasDiffusionSchedulers,
116
+ force_zeros_for_empty_prompt: bool = True,
117
+ ):
118
+ super().__init__()
119
+
120
+ self.register_modules(
121
+ vae=vae,
122
+ text_encoder=text_encoder,
123
+ text_encoder_2=text_encoder_2,
124
+ tokenizer=tokenizer,
125
+ tokenizer_2=tokenizer_2,
126
+ unet=unet,
127
+ scheduler=scheduler,
128
+ )
129
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
130
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
131
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
132
+ self.default_sample_size = self.unet.config.sample_size
133
+
134
+ self.watermark = StableDiffusionXLWatermarker()
135
+
136
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
137
+ def enable_vae_slicing(self):
138
+ r"""
139
+ Enable sliced VAE decoding.
140
+
141
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
142
+ steps. This is useful to save some memory and allow larger batch sizes.
143
+ """
144
+ self.vae.enable_slicing()
145
+
146
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
147
+ def disable_vae_slicing(self):
148
+ r"""
149
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
150
+ computing decoding in one step.
151
+ """
152
+ self.vae.disable_slicing()
153
+
154
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
155
+ def enable_vae_tiling(self):
156
+ r"""
157
+ Enable tiled VAE decoding.
158
+
159
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
160
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
161
+ """
162
+ self.vae.enable_tiling()
163
+
164
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
165
+ def disable_vae_tiling(self):
166
+ r"""
167
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
168
+ computing decoding in one step.
169
+ """
170
+ self.vae.disable_tiling()
171
+
172
+ def enable_sequential_cpu_offload(self, gpu_id=0):
173
+ r"""
174
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
175
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
176
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
177
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
178
+ `enable_model_cpu_offload`, but performance is lower.
179
+ """
180
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
181
+ from accelerate import cpu_offload
182
+ else:
183
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
184
+
185
+ device = torch.device(f"cuda:{gpu_id}")
186
+
187
+ if self.device.type != "cpu":
188
+ self.to("cpu", silence_dtype_warnings=True)
189
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
190
+
191
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.text_encoder_2, self.vae]:
192
+ cpu_offload(cpu_offloaded_model, device)
193
+
194
+ def enable_model_cpu_offload(self, gpu_id=0):
195
+ r"""
196
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
197
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
198
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
199
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
200
+ """
201
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
202
+ from accelerate import cpu_offload_with_hook
203
+ else:
204
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
205
+
206
+ device = torch.device(f"cuda:{gpu_id}")
207
+
208
+ if self.device.type != "cpu":
209
+ self.to("cpu", silence_dtype_warnings=True)
210
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
211
+
212
+ model_sequence = (
213
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
214
+ )
215
+ model_sequence.extend([self.unet, self.vae])
216
+
217
+ hook = None
218
+ for cpu_offloaded_model in model_sequence:
219
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
220
+
221
+ # We'll offload the last model manually.
222
+ self.final_offload_hook = hook
223
+
224
+ @property
225
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
226
+ def _execution_device(self):
227
+ r"""
228
+ Returns the device on which the pipeline's models will be executed. After calling
229
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
230
+ hooks.
231
+ """
232
+ if not hasattr(self.unet, "_hf_hook"):
233
+ return self.device
234
+ for module in self.unet.modules():
235
+ if (
236
+ hasattr(module, "_hf_hook")
237
+ and hasattr(module._hf_hook, "execution_device")
238
+ and module._hf_hook.execution_device is not None
239
+ ):
240
+ return torch.device(module._hf_hook.execution_device)
241
+ return self.device
242
+
243
+ def encode_prompt(
244
+ self,
245
+ prompt,
246
+ device: Optional[torch.device] = None,
247
+ num_images_per_prompt: int = 1,
248
+ do_classifier_free_guidance: bool = True,
249
+ negative_prompt=None,
250
+ prompt_embeds: Optional[torch.FloatTensor] = None,
251
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
252
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
253
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
254
+ lora_scale: Optional[float] = None,
255
+ ):
256
+ r"""
257
+ Encodes the prompt into text encoder hidden states.
258
+
259
+ Args:
260
+ prompt (`str` or `List[str]`, *optional*):
261
+ prompt to be encoded
262
+ device: (`torch.device`):
263
+ torch device
264
+ num_images_per_prompt (`int`):
265
+ number of images that should be generated per prompt
266
+ do_classifier_free_guidance (`bool`):
267
+ whether to use classifier free guidance or not
268
+ negative_prompt (`str` or `List[str]`, *optional*):
269
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
270
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
271
+ less than `1`).
272
+ prompt_embeds (`torch.FloatTensor`, *optional*):
273
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
274
+ provided, text embeddings will be generated from `prompt` input argument.
275
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
276
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
277
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
278
+ argument.
279
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
280
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
281
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
282
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
283
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
284
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
285
+ input argument.
286
+ lora_scale (`float`, *optional*):
287
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
288
+ """
289
+ device = device or self._execution_device
290
+
291
+ # set lora scale so that monkey patched LoRA
292
+ # function of text encoder can correctly access it
293
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
294
+ self._lora_scale = lora_scale
295
+
296
+ if prompt is not None and isinstance(prompt, str):
297
+ batch_size = 1
298
+ elif prompt is not None and isinstance(prompt, list):
299
+ batch_size = len(prompt)
300
+ else:
301
+ batch_size = prompt_embeds.shape[0]
302
+
303
+ # Define tokenizers and text encoders
304
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
305
+ text_encoders = (
306
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
307
+ )
308
+
309
+ if prompt_embeds is None:
310
+ # textual inversion: procecss multi-vector tokens if necessary
311
+ prompt_embeds_list = []
312
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
313
+ if isinstance(self, TextualInversionLoaderMixin):
314
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
315
+
316
+ text_inputs = tokenizer(
317
+ prompt,
318
+ padding="max_length",
319
+ max_length=tokenizer.model_max_length,
320
+ truncation=True,
321
+ return_tensors="pt",
322
+ )
323
+ text_input_ids = text_inputs.input_ids
324
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
325
+
326
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
327
+ text_input_ids, untruncated_ids
328
+ ):
329
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
330
+ logger.warning(
331
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
332
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
333
+ )
334
+
335
+ prompt_embeds = text_encoder(
336
+ text_input_ids.to(device),
337
+ output_hidden_states=True,
338
+ )
339
+
340
+ # We are only ALWAYS interested in the pooled output of the final text encoder
341
+ pooled_prompt_embeds = prompt_embeds[0]
342
+ prompt_embeds = prompt_embeds.hidden_states[-2]
343
+
344
+ bs_embed, seq_len, _ = prompt_embeds.shape
345
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
346
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
347
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
348
+
349
+ prompt_embeds_list.append(prompt_embeds)
350
+
351
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
352
+
353
+ # get unconditional embeddings for classifier free guidance
354
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
355
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
356
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
357
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
358
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
359
+ negative_prompt = negative_prompt or ""
360
+ uncond_tokens: List[str]
361
+ if prompt is not None and type(prompt) is not type(negative_prompt):
362
+ raise TypeError(
363
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
364
+ f" {type(prompt)}."
365
+ )
366
+ elif isinstance(negative_prompt, str):
367
+ uncond_tokens = [negative_prompt]
368
+ elif batch_size != len(negative_prompt):
369
+ raise ValueError(
370
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
371
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
372
+ " the batch size of `prompt`."
373
+ )
374
+ else:
375
+ uncond_tokens = negative_prompt
376
+
377
+ negative_prompt_embeds_list = []
378
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
379
+ # textual inversion: procecss multi-vector tokens if necessary
380
+ if isinstance(self, TextualInversionLoaderMixin):
381
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, tokenizer)
382
+
383
+ max_length = prompt_embeds.shape[1]
384
+ uncond_input = tokenizer(
385
+ uncond_tokens,
386
+ padding="max_length",
387
+ max_length=max_length,
388
+ truncation=True,
389
+ return_tensors="pt",
390
+ )
391
+
392
+ negative_prompt_embeds = text_encoder(
393
+ uncond_input.input_ids.to(device),
394
+ output_hidden_states=True,
395
+ )
396
+ # We are only ALWAYS interested in the pooled output of the final text encoder
397
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
398
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
399
+
400
+ if do_classifier_free_guidance:
401
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
402
+ seq_len = negative_prompt_embeds.shape[1]
403
+
404
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=text_encoder.dtype, device=device)
405
+
406
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
407
+ negative_prompt_embeds = negative_prompt_embeds.view(
408
+ batch_size * num_images_per_prompt, seq_len, -1
409
+ )
410
+
411
+ # For classifier free guidance, we need to do two forward passes.
412
+ # Here we concatenate the unconditional and text embeddings into a single batch
413
+ # to avoid doing two forward passes
414
+
415
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
416
+
417
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
418
+
419
+ bs_embed = pooled_prompt_embeds.shape[0]
420
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
421
+ bs_embed * num_images_per_prompt, -1
422
+ )
423
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
424
+ bs_embed * num_images_per_prompt, -1
425
+ )
426
+
427
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
428
+
429
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
430
+ def prepare_extra_step_kwargs(self, generator, eta):
431
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
432
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
433
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
434
+ # and should be between [0, 1]
435
+
436
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
437
+ extra_step_kwargs = {}
438
+ if accepts_eta:
439
+ extra_step_kwargs["eta"] = eta
440
+
441
+ # check if the scheduler accepts generator
442
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
443
+ if accepts_generator:
444
+ extra_step_kwargs["generator"] = generator
445
+ return extra_step_kwargs
446
+
447
+ def check_inputs(
448
+ self,
449
+ prompt,
450
+ height,
451
+ width,
452
+ callback_steps,
453
+ negative_prompt=None,
454
+ prompt_embeds=None,
455
+ negative_prompt_embeds=None,
456
+ pooled_prompt_embeds=None,
457
+ negative_pooled_prompt_embeds=None,
458
+ ):
459
+ if height % 8 != 0 or width % 8 != 0:
460
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
461
+
462
+ if (callback_steps is None) or (
463
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
464
+ ):
465
+ raise ValueError(
466
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
467
+ f" {type(callback_steps)}."
468
+ )
469
+
470
+ if prompt is not None and prompt_embeds is not None:
471
+ raise ValueError(
472
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
473
+ " only forward one of the two."
474
+ )
475
+ elif prompt is None and prompt_embeds is None:
476
+ raise ValueError(
477
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
478
+ )
479
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
480
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
481
+
482
+ if negative_prompt is not None and negative_prompt_embeds is not None:
483
+ raise ValueError(
484
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
485
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
486
+ )
487
+
488
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
489
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
490
+ raise ValueError(
491
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
492
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
493
+ f" {negative_prompt_embeds.shape}."
494
+ )
495
+
496
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
497
+ raise ValueError(
498
+ "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`."
499
+ )
500
+
501
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
502
+ raise ValueError(
503
+ "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`."
504
+ )
505
+
506
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
507
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
508
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
509
+ if isinstance(generator, list) and len(generator) != batch_size:
510
+ raise ValueError(
511
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
512
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
513
+ )
514
+
515
+ if latents is None:
516
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
517
+ else:
518
+ latents = latents.to(device)
519
+
520
+ # scale the initial noise by the standard deviation required by the scheduler
521
+ latents = latents * self.scheduler.init_noise_sigma
522
+ return latents
523
+
524
+ def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
525
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
526
+
527
+ passed_add_embed_dim = (
528
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
529
+ )
530
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
531
+
532
+ if expected_add_embed_dim != passed_add_embed_dim:
533
+ raise ValueError(
534
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
535
+ )
536
+
537
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
538
+ return add_time_ids
539
+
540
+ @torch.no_grad()
541
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
542
+ def __call__(
543
+ self,
544
+ prompt: Union[str, List[str]] = None,
545
+ height: Optional[int] = None,
546
+ width: Optional[int] = None,
547
+ num_inference_steps: int = 50,
548
+ guidance_scale: float = 5.0,
549
+ negative_prompt: Optional[Union[str, List[str]]] = None,
550
+ num_images_per_prompt: Optional[int] = 1,
551
+ eta: float = 0.0,
552
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
553
+ latents: Optional[torch.FloatTensor] = None,
554
+ prompt_embeds: Optional[torch.FloatTensor] = None,
555
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
556
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
557
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
558
+ output_type: Optional[str] = "pil",
559
+ return_dict: bool = True,
560
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
561
+ callback_steps: int = 1,
562
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
563
+ guidance_rescale: float = 0.0,
564
+ original_size: Optional[Tuple[int, int]] = None,
565
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
566
+ target_size: Optional[Tuple[int, int]] = None,
567
+ ):
568
+ r"""
569
+ Function invoked when calling the pipeline for generation.
570
+
571
+ Args:
572
+ prompt (`str` or `List[str]`, *optional*):
573
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
574
+ instead.
575
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
576
+ The height in pixels of the generated image.
577
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
578
+ The width in pixels of the generated image.
579
+ num_inference_steps (`int`, *optional*, defaults to 50):
580
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
581
+ expense of slower inference.
582
+ guidance_scale (`float`, *optional*, defaults to 7.5):
583
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
584
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
585
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
586
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
587
+ usually at the expense of lower image quality.
588
+ negative_prompt (`str` or `List[str]`, *optional*):
589
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
590
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
591
+ less than `1`).
592
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
593
+ The number of images to generate per prompt.
594
+ eta (`float`, *optional*, defaults to 0.0):
595
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
596
+ [`schedulers.DDIMScheduler`], will be ignored for others.
597
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
598
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
599
+ to make generation deterministic.
600
+ latents (`torch.FloatTensor`, *optional*):
601
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
602
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
603
+ tensor will ge generated by sampling using the supplied random `generator`.
604
+ prompt_embeds (`torch.FloatTensor`, *optional*):
605
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
606
+ provided, text embeddings will be generated from `prompt` input argument.
607
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
608
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
609
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
610
+ argument.
611
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
612
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
613
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
614
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
615
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
616
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
617
+ input argument.
618
+ output_type (`str`, *optional*, defaults to `"pil"`):
619
+ The output format of the generate image. Choose between
620
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
621
+ return_dict (`bool`, *optional*, defaults to `True`):
622
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
623
+ plain tuple.
624
+ callback (`Callable`, *optional*):
625
+ A function that will be called every `callback_steps` steps during inference. The function will be
626
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
627
+ callback_steps (`int`, *optional*, defaults to 1):
628
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
629
+ called at every step.
630
+ cross_attention_kwargs (`dict`, *optional*):
631
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
632
+ `self.processor` in
633
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
634
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
635
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
636
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
637
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
638
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
639
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
640
+ TODO
641
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
642
+ TODO
643
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
644
+ TODO
645
+
646
+ Examples:
647
+
648
+ Returns:
649
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
650
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
651
+ `tuple. When returning a tuple, the first element is a list with the generated images, and the second
652
+ element is a list of `bool`s denoting whether the corresponding generated image likely represents
653
+ "not-safe-for-work" (nsfw) content, according to the `safety_checker`.
654
+ """
655
+ # 0. Default height and width to unet
656
+ height = height or self.default_sample_size * self.vae_scale_factor
657
+ width = width or self.default_sample_size * self.vae_scale_factor
658
+
659
+ original_size = original_size or (height, width)
660
+ target_size = target_size or (height, width)
661
+
662
+ # 1. Check inputs. Raise error if not correct
663
+ self.check_inputs(
664
+ prompt,
665
+ height,
666
+ width,
667
+ callback_steps,
668
+ negative_prompt,
669
+ prompt_embeds,
670
+ negative_prompt_embeds,
671
+ pooled_prompt_embeds,
672
+ negative_pooled_prompt_embeds,
673
+ )
674
+
675
+ # 2. Define call parameters
676
+ if prompt is not None and isinstance(prompt, str):
677
+ batch_size = 1
678
+ elif prompt is not None and isinstance(prompt, list):
679
+ batch_size = len(prompt)
680
+ else:
681
+ batch_size = prompt_embeds.shape[0]
682
+
683
+ device = self._execution_device
684
+
685
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
686
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
687
+ # corresponds to doing no classifier free guidance.
688
+ do_classifier_free_guidance = guidance_scale > 1.0
689
+
690
+ # 3. Encode input prompt
691
+ text_encoder_lora_scale = (
692
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
693
+ )
694
+ (
695
+ prompt_embeds,
696
+ negative_prompt_embeds,
697
+ pooled_prompt_embeds,
698
+ negative_pooled_prompt_embeds,
699
+ ) = self.encode_prompt(
700
+ prompt,
701
+ device,
702
+ num_images_per_prompt,
703
+ do_classifier_free_guidance,
704
+ negative_prompt,
705
+ prompt_embeds=prompt_embeds,
706
+ negative_prompt_embeds=negative_prompt_embeds,
707
+ pooled_prompt_embeds=pooled_prompt_embeds,
708
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
709
+ lora_scale=text_encoder_lora_scale,
710
+ )
711
+
712
+ # 4. Prepare timesteps
713
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
714
+
715
+ timesteps = self.scheduler.timesteps
716
+
717
+ # 5. Prepare latent variables
718
+ num_channels_latents = self.unet.config.in_channels
719
+ latents = self.prepare_latents(
720
+ batch_size * num_images_per_prompt,
721
+ num_channels_latents,
722
+ height,
723
+ width,
724
+ prompt_embeds.dtype,
725
+ device,
726
+ generator,
727
+ latents,
728
+ )
729
+
730
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
731
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
732
+
733
+ # 7. Prepare added time ids & embeddings
734
+ add_text_embeds = pooled_prompt_embeds
735
+ add_time_ids = self._get_add_time_ids(
736
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
737
+ )
738
+
739
+ if do_classifier_free_guidance:
740
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
741
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
742
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
743
+
744
+ prompt_embeds = prompt_embeds.to(device)
745
+ add_text_embeds = add_text_embeds.to(device)
746
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
747
+
748
+ # 8. Denoising loop
749
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
750
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
751
+ for i, t in enumerate(timesteps):
752
+ # expand the latents if we are doing classifier free guidance
753
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
754
+
755
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
756
+
757
+ # predict the noise residual
758
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
759
+ noise_pred = self.unet(
760
+ latent_model_input,
761
+ t,
762
+ encoder_hidden_states=prompt_embeds,
763
+ cross_attention_kwargs=cross_attention_kwargs,
764
+ added_cond_kwargs=added_cond_kwargs,
765
+ return_dict=False,
766
+ )[0]
767
+
768
+ # perform guidance
769
+ if do_classifier_free_guidance:
770
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
771
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
772
+
773
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
774
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
775
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
776
+
777
+ # compute the previous noisy sample x_t -> x_t-1
778
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
779
+
780
+ # call the callback, if provided
781
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
782
+ progress_bar.update()
783
+ if callback is not None and i % callback_steps == 0:
784
+ callback(i, t, latents)
785
+
786
+ # make sure the VAE is in float32 mode, as it overflows in float16
787
+ self.vae.to(dtype=torch.float32)
788
+
789
+ use_torch_2_0_or_xformers = isinstance(
790
+ self.vae.decoder.mid_block.attentions[0].processor,
791
+ (
792
+ AttnProcessor2_0,
793
+ XFormersAttnProcessor,
794
+ LoRAXFormersAttnProcessor,
795
+ LoRAAttnProcessor2_0,
796
+ ),
797
+ )
798
+ # if xformers or torch_2_0 is used attention block does not need
799
+ # to be in float32 which can save lots of memory
800
+ if use_torch_2_0_or_xformers:
801
+ self.vae.post_quant_conv.to(latents.dtype)
802
+ self.vae.decoder.conv_in.to(latents.dtype)
803
+ self.vae.decoder.mid_block.to(latents.dtype)
804
+ else:
805
+ latents = latents.float()
806
+
807
+ if not output_type == "latent":
808
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
809
+ else:
810
+ image = latents
811
+ return StableDiffusionXLPipelineOutput(images=image)
812
+
813
+ image = self.watermark.apply_watermark(image)
814
+ image = self.image_processor.postprocess(image, output_type=output_type)
815
+
816
+ # Offload last model to CPU
817
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
818
+ self.final_offload_hook.offload()
819
+
820
+ if not return_dict:
821
+ return (image,)
822
+
823
+ return StableDiffusionXLPipelineOutput(images=image)